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 "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "Support/STLExtras.h"
29 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
30 int yylex(); // declaration" of xxx warnings.
35 static Module *ParserResult;
36 std::string CurFilename;
38 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
39 // relating to upreferences in the input stream.
41 //#define DEBUG_UPREFS 1
43 #define UR_OUT(X) std::cerr << X
48 #define YYERROR_VERBOSE 1
50 // HACK ALERT: This variable is used to implement the automatic conversion of
51 // variable argument instructions from their old to new forms. When this
52 // compatiblity "Feature" is removed, this should be too.
54 static BasicBlock *CurBB;
55 static bool ObsoleteVarArgs;
58 // This contains info used when building the body of a function. It is
59 // destroyed when the function is completed.
61 typedef std::vector<Value *> ValueList; // Numbered defs
62 static void ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
63 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
65 static struct PerModuleInfo {
66 Module *CurrentModule;
67 std::map<const Type *, ValueList> Values; // Module level numbered definitions
68 std::map<const Type *,ValueList> LateResolveValues;
69 std::vector<PATypeHolder> Types;
70 std::map<ValID, PATypeHolder> LateResolveTypes;
72 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
73 // references to global values. Global values may be referenced before they
74 // are defined, and if so, the temporary object that they represent is held
75 // here. This is used for forward references of ConstantPointerRefs.
77 typedef std::map<std::pair<const PointerType *,
78 ValID>, GlobalValue*> GlobalRefsType;
79 GlobalRefsType GlobalRefs;
82 // If we could not resolve some functions at function compilation time
83 // (calls to functions before they are defined), resolve them now... Types
84 // are resolved when the constant pool has been completely parsed.
86 ResolveDefinitions(LateResolveValues);
88 // Check to make sure that all global value forward references have been
91 if (!GlobalRefs.empty()) {
92 std::string UndefinedReferences = "Unresolved global references exist:\n";
94 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
96 UndefinedReferences += " " + I->first.first->getDescription() + " " +
97 I->first.second.getName() + "\n";
99 ThrowException(UndefinedReferences);
102 Values.clear(); // Clear out function local definitions
108 // DeclareNewGlobalValue - Called every time a new GV has been defined. This
109 // is used to remove things from the forward declaration map, resolving them
110 // to the correct thing as needed.
112 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
113 // Check to see if there is a forward reference to this global variable...
114 // if there is, eliminate it and patch the reference to use the new def'n.
115 GlobalRefsType::iterator I =
116 GlobalRefs.find(std::make_pair(GV->getType(), D));
118 if (I != GlobalRefs.end()) {
119 GlobalValue *OldGV = I->second; // Get the placeholder...
120 I->first.second.destroy(); // Free string memory if necessary
122 // Replace all uses of the placeholder with the new GV
123 OldGV->replaceAllUsesWith(GV);
125 // Remove OldGV from the module...
126 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(OldGV))
127 CurrentModule->getGlobalList().erase(GVar);
129 CurrentModule->getFunctionList().erase(cast<Function>(OldGV));
131 // Remove the map entry for the global now that it has been created...
138 static struct PerFunctionInfo {
139 Function *CurrentFunction; // Pointer to current function being created
141 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
142 std::map<const Type*, ValueList> LateResolveValues;
143 std::vector<PATypeHolder> Types;
144 std::map<ValID, PATypeHolder> LateResolveTypes;
145 SymbolTable LocalSymtab;
146 bool isDeclare; // Is this function a forward declararation?
148 inline PerFunctionInfo() {
153 inline void FunctionStart(Function *M) {
157 void FunctionDone() {
158 // If we could not resolve some blocks at parsing time (forward branches)
159 // resolve the branches now...
160 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
162 // Make sure to resolve any constant expr references that might exist within
163 // the function we just declared itself.
165 if (CurrentFunction->hasName()) {
166 FID = ValID::create((char*)CurrentFunction->getName().c_str());
168 // Figure out which slot number if is...
169 ValueList &List = CurModule.Values[CurrentFunction->getType()];
170 for (unsigned i = 0; ; ++i) {
171 assert(i < List.size() && "Function not found!");
172 if (List[i] == CurrentFunction) {
173 FID = ValID::create((int)i);
178 CurModule.DeclareNewGlobalValue(CurrentFunction, FID);
180 Values.clear(); // Clear out function local definitions
181 Types.clear(); // Clear out function local types
182 LocalSymtab.clear(); // Clear out function local symbol table
186 } CurFun; // Info for the current function...
188 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
191 //===----------------------------------------------------------------------===//
192 // Code to handle definitions of all the types
193 //===----------------------------------------------------------------------===//
195 static int InsertValue(Value *V,
196 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
197 if (V->hasName()) return -1; // Is this a numbered definition?
199 // Yes, insert the value into the value table...
200 ValueList &List = ValueTab[V->getType()];
202 return List.size()-1;
205 // TODO: FIXME when Type are not const
206 static void InsertType(const Type *Ty, std::vector<PATypeHolder> &Types) {
210 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
212 case ValID::NumberVal: { // Is it a numbered definition?
213 unsigned Num = (unsigned)D.Num;
215 // Module constants occupy the lowest numbered slots...
216 if (Num < CurModule.Types.size())
217 return CurModule.Types[Num];
219 Num -= CurModule.Types.size();
221 // Check that the number is within bounds...
222 if (Num <= CurFun.Types.size())
223 return CurFun.Types[Num];
226 case ValID::NameVal: { // Is it a named definition?
227 std::string Name(D.Name);
228 SymbolTable *SymTab = 0;
230 if (inFunctionScope()) {
231 SymTab = &CurFun.CurrentFunction->getSymbolTable();
232 N = SymTab->lookupType(Name);
236 // Symbol table doesn't automatically chain yet... because the function
237 // hasn't been added to the module...
239 SymTab = &CurModule.CurrentModule->getSymbolTable();
240 N = SymTab->lookupType(Name);
244 D.destroy(); // Free old strdup'd memory...
245 return cast<Type>(N);
248 ThrowException("Internal parser error: Invalid symbol type reference!");
251 // If we reached here, we referenced either a symbol that we don't know about
252 // or an id number that hasn't been read yet. We may be referencing something
253 // forward, so just create an entry to be resolved later and get to it...
255 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
257 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
258 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
260 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
261 if (I != LateResolver.end()) {
265 Type *Typ = OpaqueType::get();
266 LateResolver.insert(std::make_pair(D, Typ));
270 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
271 SymbolTable &SymTab =
272 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
273 CurModule.CurrentModule->getSymbolTable();
274 return SymTab.lookup(Ty, Name);
277 // getValNonImprovising - Look up the value specified by the provided type and
278 // the provided ValID. If the value exists and has already been defined, return
279 // it. Otherwise return null.
281 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
282 if (isa<FunctionType>(Ty))
283 ThrowException("Functions are not values and "
284 "must be referenced as pointers");
287 case ValID::NumberVal: { // Is it a numbered definition?
288 unsigned Num = (unsigned)D.Num;
290 // Module constants occupy the lowest numbered slots...
291 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
292 if (VI != CurModule.Values.end()) {
293 if (Num < VI->second.size())
294 return VI->second[Num];
295 Num -= VI->second.size();
298 // Make sure that our type is within bounds
299 VI = CurFun.Values.find(Ty);
300 if (VI == CurFun.Values.end()) return 0;
302 // Check that the number is within bounds...
303 if (VI->second.size() <= Num) return 0;
305 return VI->second[Num];
308 case ValID::NameVal: { // Is it a named definition?
309 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
310 if (N == 0) return 0;
312 D.destroy(); // Free old strdup'd memory...
316 // Check to make sure that "Ty" is an integral type, and that our
317 // value will fit into the specified type...
318 case ValID::ConstSIntVal: // Is it a constant pool reference??
319 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
320 ThrowException("Signed integral constant '" +
321 itostr(D.ConstPool64) + "' is invalid for type '" +
322 Ty->getDescription() + "'!");
323 return ConstantSInt::get(Ty, D.ConstPool64);
325 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
326 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
327 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
328 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
329 "' is invalid or out of range!");
330 } else { // This is really a signed reference. Transmogrify.
331 return ConstantSInt::get(Ty, D.ConstPool64);
334 return ConstantUInt::get(Ty, D.UConstPool64);
337 case ValID::ConstFPVal: // Is it a floating point const pool reference?
338 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
339 ThrowException("FP constant invalid for type!!");
340 return ConstantFP::get(Ty, D.ConstPoolFP);
342 case ValID::ConstNullVal: // Is it a null value?
343 if (!isa<PointerType>(Ty))
344 ThrowException("Cannot create a a non pointer null!");
345 return ConstantPointerNull::get(cast<PointerType>(Ty));
347 case ValID::ConstantVal: // Fully resolved constant?
348 if (D.ConstantValue->getType() != Ty)
349 ThrowException("Constant expression type different from required type!");
350 return D.ConstantValue;
353 assert(0 && "Unhandled case!");
357 assert(0 && "Unhandled case!");
362 // getVal - This function is identical to getValNonImprovising, except that if a
363 // value is not already defined, it "improvises" by creating a placeholder var
364 // that looks and acts just like the requested variable. When the value is
365 // defined later, all uses of the placeholder variable are replaced with the
368 static Value *getVal(const Type *Ty, const ValID &D) {
370 // See if the value has already been defined...
371 Value *V = getValNonImprovising(Ty, D);
374 // If we reached here, we referenced either a symbol that we don't know about
375 // or an id number that hasn't been read yet. We may be referencing something
376 // forward, so just create an entry to be resolved later and get to it...
379 switch (Ty->getTypeID()) {
380 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
381 default: d = new ValuePlaceHolder(Ty, D); break;
384 assert(d != 0 && "How did we not make something?");
385 if (inFunctionScope())
386 InsertValue(d, CurFun.LateResolveValues);
388 InsertValue(d, CurModule.LateResolveValues);
393 //===----------------------------------------------------------------------===//
394 // Code to handle forward references in instructions
395 //===----------------------------------------------------------------------===//
397 // This code handles the late binding needed with statements that reference
398 // values not defined yet... for example, a forward branch, or the PHI node for
401 // This keeps a table (CurFun.LateResolveValues) of all such forward references
402 // and back patchs after we are done.
405 // ResolveDefinitions - If we could not resolve some defs at parsing
406 // time (forward branches, phi functions for loops, etc...) resolve the
409 static void ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
410 std::map<const Type*,ValueList> *FutureLateResolvers) {
411 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
412 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
413 E = LateResolvers.end(); LRI != E; ++LRI) {
414 ValueList &List = LRI->second;
415 while (!List.empty()) {
416 Value *V = List.back();
418 ValID &DID = getValIDFromPlaceHolder(V);
420 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
422 V->replaceAllUsesWith(TheRealValue);
424 } else if (FutureLateResolvers) {
425 // Functions have their unresolved items forwarded to the module late
427 InsertValue(V, *FutureLateResolvers);
429 if (DID.Type == ValID::NameVal)
430 ThrowException("Reference to an invalid definition: '" +DID.getName()+
431 "' of type '" + V->getType()->getDescription() + "'",
432 getLineNumFromPlaceHolder(V));
434 ThrowException("Reference to an invalid definition: #" +
435 itostr(DID.Num) + " of type '" +
436 V->getType()->getDescription() + "'",
437 getLineNumFromPlaceHolder(V));
442 LateResolvers.clear();
445 // ResolveTypeTo - A brand new type was just declared. This means that (if
446 // name is not null) things referencing Name can be resolved. Otherwise, things
447 // refering to the number can be resolved. Do this now.
449 static void ResolveTypeTo(char *Name, const Type *ToTy) {
450 std::vector<PATypeHolder> &Types = inFunctionScope() ?
451 CurFun.Types : CurModule.Types;
454 if (Name) D = ValID::create(Name);
455 else D = ValID::create((int)Types.size());
457 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
458 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
460 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
461 if (I != LateResolver.end()) {
462 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
463 LateResolver.erase(I);
467 // ResolveTypes - At this point, all types should be resolved. Any that aren't
470 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
471 if (!LateResolveTypes.empty()) {
472 const ValID &DID = LateResolveTypes.begin()->first;
474 if (DID.Type == ValID::NameVal)
475 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
477 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
482 // setValueName - Set the specified value to the name given. The name may be
483 // null potentially, in which case this is a noop. The string passed in is
484 // assumed to be a malloc'd string buffer, and is freed by this function.
486 // This function returns true if the value has already been defined, but is
487 // allowed to be redefined in the specified context. If the name is a new name
488 // for the typeplane, false is returned.
490 static bool setValueName(Value *V, char *NameStr) {
491 if (NameStr == 0) return false;
493 std::string Name(NameStr); // Copy string
494 free(NameStr); // Free old string
496 if (V->getType() == Type::VoidTy)
497 ThrowException("Can't assign name '" + Name +
498 "' to a null valued instruction!");
500 SymbolTable &ST = inFunctionScope() ?
501 CurFun.CurrentFunction->getSymbolTable() :
502 CurModule.CurrentModule->getSymbolTable();
504 Value *Existing = ST.lookup(V->getType(), Name);
506 if (Existing) { // Inserting a name that is already defined???
507 // We are a simple redefinition of a value, check to see if it
508 // is defined the same as the old one...
509 if (const Constant *C = dyn_cast<Constant>(Existing)) {
510 if (C == V) return true; // Constants are equal to themselves
511 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
512 // We are allowed to redefine a global variable in two circumstances:
513 // 1. If at least one of the globals is uninitialized or
514 // 2. If both initializers have the same value.
516 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
517 if (!EGV->hasInitializer() || !GV->hasInitializer() ||
518 EGV->getInitializer() == GV->getInitializer()) {
520 // Make sure the existing global version gets the initializer! Make
521 // sure that it also gets marked const if the new version is.
522 if (GV->hasInitializer() && !EGV->hasInitializer())
523 EGV->setInitializer(GV->getInitializer());
524 if (GV->isConstant())
525 EGV->setConstant(true);
526 EGV->setLinkage(GV->getLinkage());
528 delete GV; // Destroy the duplicate!
529 return true; // They are equivalent!
534 ThrowException("Redefinition of value named '" + Name + "' in the '" +
535 V->getType()->getDescription() + "' type plane!");
539 V->setName(Name, &ST);
541 // If we're in function scope
542 if (inFunctionScope()) {
543 // Look up the symbol in the function's local symboltable
544 Existing = CurFun.LocalSymtab.lookup(V->getType(),Name);
546 // If it already exists
549 ThrowException("Redefinition of value named '" + Name + "' in the '" +
550 V->getType()->getDescription() + "' type plane!");
552 // otherwise, since it doesn't exist
555 CurFun.LocalSymtab.insert(V);
561 // setTypeName - Set the specified type to the name given. The name may be
562 // null potentially, in which case this is a noop. The string passed in is
563 // assumed to be a malloc'd string buffer, and is freed by this function.
565 // This function returns true if the type has already been defined, but is
566 // allowed to be redefined in the specified context. If the name is a new name
567 // for the type plane, it is inserted and false is returned.
568 static bool setTypeName(Type *T, char *NameStr) {
569 if (NameStr == 0) return false;
571 std::string Name(NameStr); // Copy string
572 free(NameStr); // Free old string
574 // We don't allow assigning names to void type
575 if (T == Type::VoidTy)
576 ThrowException("Can't assign name '" + Name + "' to the null type!");
578 SymbolTable &ST = inFunctionScope() ?
579 CurFun.CurrentFunction->getSymbolTable() :
580 CurModule.CurrentModule->getSymbolTable();
582 Type *Existing = ST.lookupType(Name);
584 if (Existing) { // Inserting a name that is already defined???
585 // There is only one case where this is allowed: when we are refining an
586 // opaque type. In this case, Existing will be an opaque type.
587 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
588 // We ARE replacing an opaque type!
589 ((OpaqueType*)OpTy)->refineAbstractTypeTo(T);
593 // Otherwise, this is an attempt to redefine a type. That's okay if
594 // the redefinition is identical to the original. This will be so if
595 // Existing and T point to the same Type object. In this one case we
596 // allow the equivalent redefinition.
597 if (Existing == T) return true; // Yes, it's equal.
599 // Any other kind of (non-equivalent) redefinition is an error.
600 ThrowException("Redefinition of type named '" + Name + "' in the '" +
601 T->getDescription() + "' type plane!");
604 // Okay, its a newly named type. Set its name.
605 if (!Name.empty()) ST.insert(Name, T);
607 // If we're in function scope
608 if (inFunctionScope()) {
609 // Look up the symbol in the function's local symboltable
610 Existing = CurFun.LocalSymtab.lookupType(Name);
612 // If it already exists
615 ThrowException("Redefinition of type named '" + Name + "' in the '" +
616 T->getDescription() + "' type plane in function scope!");
618 // otherwise, since it doesn't exist
621 CurFun.LocalSymtab.insert(Name,T);
627 //===----------------------------------------------------------------------===//
628 // Code for handling upreferences in type names...
631 // TypeContains - Returns true if Ty directly contains E in it.
633 static bool TypeContains(const Type *Ty, const Type *E) {
634 return find(Ty->subtype_begin(), Ty->subtype_end(), E) != Ty->subtype_end();
639 // NestingLevel - The number of nesting levels that need to be popped before
640 // this type is resolved.
641 unsigned NestingLevel;
643 // LastContainedTy - This is the type at the current binding level for the
644 // type. Every time we reduce the nesting level, this gets updated.
645 const Type *LastContainedTy;
647 // UpRefTy - This is the actual opaque type that the upreference is
651 UpRefRecord(unsigned NL, OpaqueType *URTy)
652 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
656 // UpRefs - A list of the outstanding upreferences that need to be resolved.
657 static std::vector<UpRefRecord> UpRefs;
659 /// HandleUpRefs - Every time we finish a new layer of types, this function is
660 /// called. It loops through the UpRefs vector, which is a list of the
661 /// currently active types. For each type, if the up reference is contained in
662 /// the newly completed type, we decrement the level count. When the level
663 /// count reaches zero, the upreferenced type is the type that is passed in:
664 /// thus we can complete the cycle.
666 static PATypeHolder HandleUpRefs(const Type *ty) {
667 if (!ty->isAbstract()) return ty;
669 UR_OUT("Type '" << Ty->getDescription() <<
670 "' newly formed. Resolving upreferences.\n" <<
671 UpRefs.size() << " upreferences active!\n");
673 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
674 // to zero), we resolve them all together before we resolve them to Ty. At
675 // the end of the loop, if there is anything to resolve to Ty, it will be in
677 OpaqueType *TypeToResolve = 0;
679 for (unsigned i = 0; i != UpRefs.size(); ++i) {
680 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
681 << UpRefs[i].second->getDescription() << ") = "
682 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
683 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
684 // Decrement level of upreference
685 unsigned Level = --UpRefs[i].NestingLevel;
686 UpRefs[i].LastContainedTy = Ty;
687 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
688 if (Level == 0) { // Upreference should be resolved!
689 if (!TypeToResolve) {
690 TypeToResolve = UpRefs[i].UpRefTy;
692 UR_OUT(" * Resolving upreference for "
693 << UpRefs[i].second->getDescription() << "\n";
694 std::string OldName = UpRefs[i].UpRefTy->getDescription());
695 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
696 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
697 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
699 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
700 --i; // Do not skip the next element...
706 UR_OUT(" * Resolving upreference for "
707 << UpRefs[i].second->getDescription() << "\n";
708 std::string OldName = TypeToResolve->getDescription());
709 TypeToResolve->refineAbstractTypeTo(Ty);
716 //===----------------------------------------------------------------------===//
717 // RunVMAsmParser - Define an interface to this parser
718 //===----------------------------------------------------------------------===//
720 Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
722 CurFilename = Filename;
723 llvmAsmlineno = 1; // Reset the current line number...
724 ObsoleteVarArgs = false;
726 // Allocate a new module to read
727 CurModule.CurrentModule = new Module(Filename);
730 yyparse(); // Parse the file.
732 // Clear the symbol table so it doesn't complain when it
734 CurFun.LocalSymtab.clear();
738 Module *Result = ParserResult;
740 // Check to see if they called va_start but not va_arg..
741 if (!ObsoleteVarArgs)
742 if (Function *F = Result->getNamedFunction("llvm.va_start"))
743 if (F->asize() == 1) {
744 std::cerr << "WARNING: this file uses obsolete features. "
745 << "Assemble and disassemble to update it.\n";
746 ObsoleteVarArgs = true;
750 if (ObsoleteVarArgs) {
751 // If the user is making use of obsolete varargs intrinsics, adjust them for
753 if (Function *F = Result->getNamedFunction("llvm.va_start")) {
754 assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
756 const Type *RetTy = F->getFunctionType()->getParamType(0);
757 RetTy = cast<PointerType>(RetTy)->getElementType();
758 Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
760 while (!F->use_empty()) {
761 CallInst *CI = cast<CallInst>(F->use_back());
762 Value *V = new CallInst(NF, "", CI);
763 new StoreInst(V, CI->getOperand(1), CI);
764 CI->getParent()->getInstList().erase(CI);
766 Result->getFunctionList().erase(F);
769 if (Function *F = Result->getNamedFunction("llvm.va_end")) {
770 assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
771 const Type *ArgTy = F->getFunctionType()->getParamType(0);
772 ArgTy = cast<PointerType>(ArgTy)->getElementType();
773 Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
776 while (!F->use_empty()) {
777 CallInst *CI = cast<CallInst>(F->use_back());
778 Value *V = new LoadInst(CI->getOperand(1), "", CI);
779 new CallInst(NF, V, "", CI);
780 CI->getParent()->getInstList().erase(CI);
782 Result->getFunctionList().erase(F);
785 if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
786 assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
787 const Type *ArgTy = F->getFunctionType()->getParamType(0);
788 ArgTy = cast<PointerType>(ArgTy)->getElementType();
789 Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
792 while (!F->use_empty()) {
793 CallInst *CI = cast<CallInst>(F->use_back());
794 Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
795 new StoreInst(V, CI->getOperand(1), CI);
796 CI->getParent()->getInstList().erase(CI);
798 Result->getFunctionList().erase(F);
802 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
808 } // End llvm namespace
810 using namespace llvm;
815 llvm::Module *ModuleVal;
816 llvm::Function *FunctionVal;
817 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
818 llvm::BasicBlock *BasicBlockVal;
819 llvm::TerminatorInst *TermInstVal;
820 llvm::Instruction *InstVal;
821 llvm::Constant *ConstVal;
823 const llvm::Type *PrimType;
824 llvm::PATypeHolder *TypeVal;
825 llvm::Value *ValueVal;
827 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
828 std::vector<llvm::Value*> *ValueList;
829 std::list<llvm::PATypeHolder> *TypeList;
830 std::list<std::pair<llvm::Value*,
831 llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
832 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
833 std::vector<llvm::Constant*> *ConstVector;
835 llvm::GlobalValue::LinkageTypes Linkage;
843 char *StrVal; // This memory is strdup'd!
844 llvm::ValID ValIDVal; // strdup'd memory maybe!
846 llvm::Instruction::BinaryOps BinaryOpVal;
847 llvm::Instruction::TermOps TermOpVal;
848 llvm::Instruction::MemoryOps MemOpVal;
849 llvm::Instruction::OtherOps OtherOpVal;
850 llvm::Module::Endianness Endianness;
853 %type <ModuleVal> Module FunctionList
854 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
855 %type <BasicBlockVal> BasicBlock InstructionList
856 %type <TermInstVal> BBTerminatorInst
857 %type <InstVal> Inst InstVal MemoryInst
858 %type <ConstVal> ConstVal ConstExpr
859 %type <ConstVector> ConstVector
860 %type <ArgList> ArgList ArgListH
861 %type <ArgVal> ArgVal
862 %type <PHIList> PHIList
863 %type <ValueList> ValueRefList ValueRefListE // For call param lists
864 %type <ValueList> IndexList // For GEP derived indices
865 %type <TypeList> TypeListI ArgTypeListI
866 %type <JumpTable> JumpTable
867 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
868 %type <BoolVal> OptVolatile // 'volatile' or not
869 %type <Linkage> OptLinkage
870 %type <Endianness> BigOrLittle
872 // ValueRef - Unresolved reference to a definition or BB
873 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
874 %type <ValueVal> ResolvedVal // <type> <valref> pair
875 // Tokens and types for handling constant integer values
877 // ESINT64VAL - A negative number within long long range
878 %token <SInt64Val> ESINT64VAL
880 // EUINT64VAL - A positive number within uns. long long range
881 %token <UInt64Val> EUINT64VAL
882 %type <SInt64Val> EINT64VAL
884 %token <SIntVal> SINTVAL // Signed 32 bit ints...
885 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
886 %type <SIntVal> INTVAL
887 %token <FPVal> FPVAL // Float or Double constant
890 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
891 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
892 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
893 %token <PrimType> FLOAT DOUBLE TYPE LABEL
895 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
896 %type <StrVal> Name OptName OptAssign
899 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
900 %token DECLARE GLOBAL CONSTANT VOLATILE
901 %token TO DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE WEAK APPENDING
902 %token OPAQUE NOT EXTERNAL TARGET ENDIAN POINTERSIZE LITTLE BIG
904 // Basic Block Terminating Operators
905 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND
908 %type <BinaryOpVal> BinaryOps // all the binary operators
909 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
910 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
911 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
913 // Memory Instructions
914 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
917 %type <OtherOpVal> ShiftOps
918 %token <OtherOpVal> PHI_TOK CALL CAST SELECT SHL SHR VAARG VANEXT
919 %token VA_ARG // FIXME: OBSOLETE
924 // Handle constant integer size restriction and conversion...
928 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
929 ThrowException("Value too large for type!");
934 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
935 EINT64VAL : EUINT64VAL {
936 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
937 ThrowException("Value too large for type!");
941 // Operations that are notably excluded from this list include:
942 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
944 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
945 LogicalOps : AND | OR | XOR;
946 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
947 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
949 ShiftOps : SHL | SHR;
951 // These are some types that allow classification if we only want a particular
952 // thing... for example, only a signed, unsigned, or integral type.
953 SIntType : LONG | INT | SHORT | SBYTE;
954 UIntType : ULONG | UINT | USHORT | UBYTE;
955 IntType : SIntType | UIntType;
956 FPType : FLOAT | DOUBLE;
958 // OptAssign - Value producing statements have an optional assignment component
959 OptAssign : Name '=' {
966 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
967 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
968 WEAK { $$ = GlobalValue::WeakLinkage; } |
969 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
970 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
972 //===----------------------------------------------------------------------===//
973 // Types includes all predefined types... except void, because it can only be
974 // used in specific contexts (function returning void for example). To have
975 // access to it, a user must explicitly use TypesV.
978 // TypesV includes all of 'Types', but it also includes the void type.
979 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
980 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
984 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
989 // Derived types are added later...
991 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
992 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
994 $$ = new PATypeHolder(OpaqueType::get());
997 $$ = new PATypeHolder($1);
999 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1000 $$ = new PATypeHolder(getTypeVal($1));
1003 // Include derived types in the Types production.
1005 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1006 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1007 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1008 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1009 $$ = new PATypeHolder(OT);
1010 UR_OUT("New Upreference!\n");
1012 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1013 std::vector<const Type*> Params;
1014 mapto($3->begin(), $3->end(), std::back_inserter(Params),
1015 std::mem_fun_ref(&PATypeHolder::get));
1016 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1017 if (isVarArg) Params.pop_back();
1019 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1020 delete $3; // Delete the argument list
1021 delete $1; // Delete the return type handle
1023 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1024 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1027 | '{' TypeListI '}' { // Structure type?
1028 std::vector<const Type*> Elements;
1029 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
1030 std::mem_fun_ref(&PATypeHolder::get));
1032 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1035 | '{' '}' { // Empty structure type?
1036 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1038 | UpRTypes '*' { // Pointer type?
1039 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1043 // TypeList - Used for struct declarations and as a basis for function type
1044 // declaration type lists
1046 TypeListI : UpRTypes {
1047 $$ = new std::list<PATypeHolder>();
1048 $$->push_back(*$1); delete $1;
1050 | TypeListI ',' UpRTypes {
1051 ($$=$1)->push_back(*$3); delete $3;
1054 // ArgTypeList - List of types for a function type declaration...
1055 ArgTypeListI : TypeListI
1056 | TypeListI ',' DOTDOTDOT {
1057 ($$=$1)->push_back(Type::VoidTy);
1060 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1063 $$ = new std::list<PATypeHolder>();
1066 // ConstVal - The various declarations that go into the constant pool. This
1067 // production is used ONLY to represent constants that show up AFTER a 'const',
1068 // 'constant' or 'global' token at global scope. Constants that can be inlined
1069 // into other expressions (such as integers and constexprs) are handled by the
1070 // ResolvedVal, ValueRef and ConstValueRef productions.
1072 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1073 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1075 ThrowException("Cannot make array constant with type: '" +
1076 (*$1)->getDescription() + "'!");
1077 const Type *ETy = ATy->getElementType();
1078 int NumElements = ATy->getNumElements();
1080 // Verify that we have the correct size...
1081 if (NumElements != -1 && NumElements != (int)$3->size())
1082 ThrowException("Type mismatch: constant sized array initialized with " +
1083 utostr($3->size()) + " arguments, but has size of " +
1084 itostr(NumElements) + "!");
1086 // Verify all elements are correct type!
1087 for (unsigned i = 0; i < $3->size(); i++) {
1088 if (ETy != (*$3)[i]->getType())
1089 ThrowException("Element #" + utostr(i) + " is not of type '" +
1090 ETy->getDescription() +"' as required!\nIt is of type '"+
1091 (*$3)[i]->getType()->getDescription() + "'.");
1094 $$ = ConstantArray::get(ATy, *$3);
1095 delete $1; delete $3;
1098 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1100 ThrowException("Cannot make array constant with type: '" +
1101 (*$1)->getDescription() + "'!");
1103 int NumElements = ATy->getNumElements();
1104 if (NumElements != -1 && NumElements != 0)
1105 ThrowException("Type mismatch: constant sized array initialized with 0"
1106 " arguments, but has size of " + itostr(NumElements) +"!");
1107 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1110 | Types 'c' STRINGCONSTANT {
1111 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1113 ThrowException("Cannot make array constant with type: '" +
1114 (*$1)->getDescription() + "'!");
1116 int NumElements = ATy->getNumElements();
1117 const Type *ETy = ATy->getElementType();
1118 char *EndStr = UnEscapeLexed($3, true);
1119 if (NumElements != -1 && NumElements != (EndStr-$3))
1120 ThrowException("Can't build string constant of size " +
1121 itostr((int)(EndStr-$3)) +
1122 " when array has size " + itostr(NumElements) + "!");
1123 std::vector<Constant*> Vals;
1124 if (ETy == Type::SByteTy) {
1125 for (char *C = $3; C != EndStr; ++C)
1126 Vals.push_back(ConstantSInt::get(ETy, *C));
1127 } else if (ETy == Type::UByteTy) {
1128 for (char *C = $3; C != EndStr; ++C)
1129 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1132 ThrowException("Cannot build string arrays of non byte sized elements!");
1135 $$ = ConstantArray::get(ATy, Vals);
1138 | Types '{' ConstVector '}' {
1139 const StructType *STy = dyn_cast<StructType>($1->get());
1141 ThrowException("Cannot make struct constant with type: '" +
1142 (*$1)->getDescription() + "'!");
1144 if ($3->size() != STy->getNumContainedTypes())
1145 ThrowException("Illegal number of initializers for structure type!");
1147 // Check to ensure that constants are compatible with the type initializer!
1148 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1149 if ((*$3)[i]->getType() != STy->getElementType(i))
1150 ThrowException("Expected type '" +
1151 STy->getElementType(i)->getDescription() +
1152 "' for element #" + utostr(i) +
1153 " of structure initializer!");
1155 $$ = ConstantStruct::get(STy, *$3);
1156 delete $1; delete $3;
1159 const StructType *STy = dyn_cast<StructType>($1->get());
1161 ThrowException("Cannot make struct constant with type: '" +
1162 (*$1)->getDescription() + "'!");
1164 if (STy->getNumContainedTypes() != 0)
1165 ThrowException("Illegal number of initializers for structure type!");
1167 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1171 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1173 ThrowException("Cannot make null pointer constant with type: '" +
1174 (*$1)->getDescription() + "'!");
1176 $$ = ConstantPointerNull::get(PTy);
1179 | Types SymbolicValueRef {
1180 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1182 ThrowException("Global const reference must be a pointer type!");
1184 // ConstExprs can exist in the body of a function, thus creating
1185 // ConstantPointerRefs whenever they refer to a variable. Because we are in
1186 // the context of a function, getValNonImprovising will search the functions
1187 // symbol table instead of the module symbol table for the global symbol,
1188 // which throws things all off. To get around this, we just tell
1189 // getValNonImprovising that we are at global scope here.
1191 Function *SavedCurFn = CurFun.CurrentFunction;
1192 CurFun.CurrentFunction = 0;
1194 Value *V = getValNonImprovising(Ty, $2);
1196 CurFun.CurrentFunction = SavedCurFn;
1198 // If this is an initializer for a constant pointer, which is referencing a
1199 // (currently) undefined variable, create a stub now that shall be replaced
1200 // in the future with the right type of variable.
1203 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1204 const PointerType *PT = cast<PointerType>(Ty);
1206 // First check to see if the forward references value is already created!
1207 PerModuleInfo::GlobalRefsType::iterator I =
1208 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1210 if (I != CurModule.GlobalRefs.end()) {
1211 V = I->second; // Placeholder already exists, use it...
1214 // Create a placeholder for the global variable reference...
1215 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
1217 GlobalValue::ExternalLinkage);
1218 // Keep track of the fact that we have a forward ref to recycle it
1219 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1221 // Must temporarily push this value into the module table...
1222 CurModule.CurrentModule->getGlobalList().push_back(GV);
1227 GlobalValue *GV = cast<GlobalValue>(V);
1228 $$ = ConstantPointerRef::get(GV);
1229 delete $1; // Free the type handle
1232 if ($1->get() != $2->getType())
1233 ThrowException("Mismatched types for constant expression!");
1237 | Types ZEROINITIALIZER {
1238 $$ = Constant::getNullValue($1->get());
1242 ConstVal : SIntType EINT64VAL { // integral constants
1243 if (!ConstantSInt::isValueValidForType($1, $2))
1244 ThrowException("Constant value doesn't fit in type!");
1245 $$ = ConstantSInt::get($1, $2);
1247 | UIntType EUINT64VAL { // integral constants
1248 if (!ConstantUInt::isValueValidForType($1, $2))
1249 ThrowException("Constant value doesn't fit in type!");
1250 $$ = ConstantUInt::get($1, $2);
1252 | BOOL TRUETOK { // Boolean constants
1253 $$ = ConstantBool::True;
1255 | BOOL FALSETOK { // Boolean constants
1256 $$ = ConstantBool::False;
1258 | FPType FPVAL { // Float & Double constants
1259 $$ = ConstantFP::get($1, $2);
1263 ConstExpr: CAST '(' ConstVal TO Types ')' {
1264 if (!$3->getType()->isFirstClassType())
1265 ThrowException("cast constant expression from a non-primitive type: '" +
1266 $3->getType()->getDescription() + "'!");
1267 if (!$5->get()->isFirstClassType())
1268 ThrowException("cast constant expression to a non-primitive type: '" +
1269 $5->get()->getDescription() + "'!");
1270 $$ = ConstantExpr::getCast($3, $5->get());
1273 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1274 if (!isa<PointerType>($3->getType()))
1275 ThrowException("GetElementPtr requires a pointer operand!");
1277 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1278 // indices to uint struct indices for compatibility.
1279 generic_gep_type_iterator<std::vector<Value*>::iterator>
1280 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1281 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1282 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1283 if (isa<StructType>(*GTI)) // Only change struct indices
1284 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1285 if (CUI->getType() == Type::UByteTy)
1286 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1289 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1291 ThrowException("Index list invalid for constant getelementptr!");
1293 std::vector<Constant*> IdxVec;
1294 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1295 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1296 IdxVec.push_back(C);
1298 ThrowException("Indices to constant getelementptr must be constants!");
1302 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1304 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1305 if ($3->getType() != Type::BoolTy)
1306 ThrowException("Select condition must be of boolean type!");
1307 if ($5->getType() != $7->getType())
1308 ThrowException("Select operand types must match!");
1309 $$ = ConstantExpr::getSelect($3, $5, $7);
1311 | BinaryOps '(' ConstVal ',' ConstVal ')' {
1312 if ($3->getType() != $5->getType())
1313 ThrowException("Binary operator types must match!");
1314 $$ = ConstantExpr::get($1, $3, $5);
1316 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1317 if ($5->getType() != Type::UByteTy)
1318 ThrowException("Shift count for shift constant must be unsigned byte!");
1319 if (!$3->getType()->isInteger())
1320 ThrowException("Shift constant expression requires integer operand!");
1321 $$ = ConstantExpr::get($1, $3, $5);
1325 // ConstVector - A list of comma separated constants.
1326 ConstVector : ConstVector ',' ConstVal {
1327 ($$ = $1)->push_back($3);
1330 $$ = new std::vector<Constant*>();
1335 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1336 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1339 //===----------------------------------------------------------------------===//
1340 // Rules to match Modules
1341 //===----------------------------------------------------------------------===//
1343 // Module rule: Capture the result of parsing the whole file into a result
1346 Module : FunctionList {
1347 $$ = ParserResult = $1;
1348 CurModule.ModuleDone();
1351 // FunctionList - A list of functions, preceeded by a constant pool.
1353 FunctionList : FunctionList Function {
1355 CurFun.FunctionDone();
1357 | FunctionList FunctionProto {
1360 | FunctionList IMPLEMENTATION {
1364 $$ = CurModule.CurrentModule;
1365 // Resolve circular types before we parse the body of the module
1366 ResolveTypes(CurModule.LateResolveTypes);
1369 // ConstPool - Constants with optional names assigned to them.
1370 ConstPool : ConstPool OptAssign CONST ConstVal {
1371 if (!setValueName($4, $2))
1374 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1375 // Eagerly resolve types. This is not an optimization, this is a
1376 // requirement that is due to the fact that we could have this:
1378 // %list = type { %list * }
1379 // %list = type { %list * } ; repeated type decl
1381 // If types are not resolved eagerly, then the two types will not be
1382 // determined to be the same type!
1384 ResolveTypeTo($2, $4->get());
1386 // TODO: FIXME when Type are not const
1387 if (!setTypeName(const_cast<Type*>($4->get()), $2)) {
1388 // If this is not a redefinition of a type...
1390 InsertType($4->get(),
1391 inFunctionScope() ? CurFun.Types : CurModule.Types);
1397 | ConstPool FunctionProto { // Function prototypes can be in const pool
1399 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1400 const Type *Ty = $5->getType();
1401 // Global declarations appear in Constant Pool
1402 Constant *Initializer = $5;
1403 if (Initializer == 0)
1404 ThrowException("Global value initializer is not a constant!");
1406 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1407 if (!setValueName(GV, $2)) { // If not redefining...
1408 CurModule.CurrentModule->getGlobalList().push_back(GV);
1409 int Slot = InsertValue(GV, CurModule.Values);
1412 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1414 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1415 (char*)GV->getName().c_str()));
1419 | ConstPool OptAssign EXTERNAL GlobalType Types {
1420 const Type *Ty = *$5;
1421 // Global declarations appear in Constant Pool
1422 GlobalVariable *GV = new GlobalVariable(Ty,$4,GlobalValue::ExternalLinkage);
1423 if (!setValueName(GV, $2)) { // If not redefining...
1424 CurModule.CurrentModule->getGlobalList().push_back(GV);
1425 int Slot = InsertValue(GV, CurModule.Values);
1428 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1430 assert(GV->hasName() && "Not named and not numbered!?");
1431 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1432 (char*)GV->getName().c_str()));
1437 | ConstPool TARGET TargetDefinition {
1439 | /* empty: end of list */ {
1444 BigOrLittle : BIG { $$ = Module::BigEndian; };
1445 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1447 TargetDefinition : ENDIAN '=' BigOrLittle {
1448 CurModule.CurrentModule->setEndianness($3);
1450 | POINTERSIZE '=' EUINT64VAL {
1452 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1454 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1456 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1460 //===----------------------------------------------------------------------===//
1461 // Rules to match Function Headers
1462 //===----------------------------------------------------------------------===//
1464 Name : VAR_ID | STRINGCONSTANT;
1465 OptName : Name | /*empty*/ { $$ = 0; };
1467 ArgVal : Types OptName {
1468 if (*$1 == Type::VoidTy)
1469 ThrowException("void typed arguments are invalid!");
1470 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1473 ArgListH : ArgListH ',' ArgVal {
1479 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1484 ArgList : ArgListH {
1487 | ArgListH ',' DOTDOTDOT {
1489 $$->push_back(std::pair<PATypeHolder*,
1490 char*>(new PATypeHolder(Type::VoidTy), 0));
1493 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1494 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1500 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1502 std::string FunctionName($2);
1504 if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1505 ThrowException("LLVM functions cannot return aggregate types!");
1507 std::vector<const Type*> ParamTypeList;
1508 if ($4) { // If there are arguments...
1509 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1510 I != $4->end(); ++I)
1511 ParamTypeList.push_back(I->first->get());
1514 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1515 if (isVarArg) ParamTypeList.pop_back();
1517 const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1518 const PointerType *PFT = PointerType::get(FT);
1522 // Is the function already in symtab?
1523 if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1524 // Yes it is. If this is the case, either we need to be a forward decl,
1525 // or it needs to be.
1526 if (!CurFun.isDeclare && !Fn->isExternal())
1527 ThrowException("Redefinition of function '" + FunctionName + "'!");
1529 // Make sure to strip off any argument names so we can't get conflicts...
1530 for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1533 } else { // Not already defined?
1534 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1535 CurModule.CurrentModule);
1536 InsertValue(Fn, CurModule.Values);
1537 CurModule.DeclareNewGlobalValue(Fn, ValID::create($2));
1539 free($2); // Free strdup'd memory!
1541 CurFun.FunctionStart(Fn);
1543 // Add all of the arguments we parsed to the function...
1544 if ($4) { // Is null if empty...
1545 if (isVarArg) { // Nuke the last entry
1546 assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1547 "Not a varargs marker!");
1548 delete $4->back().first;
1549 $4->pop_back(); // Delete the last entry
1551 Function::aiterator ArgIt = Fn->abegin();
1552 for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1553 I != $4->end(); ++I, ++ArgIt) {
1554 delete I->first; // Delete the typeholder...
1556 if (setValueName(ArgIt, I->second)) // Insert arg into symtab...
1557 assert(0 && "No arg redef allowed!");
1562 delete $4; // We're now done with the argument list
1566 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1568 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1569 $$ = CurFun.CurrentFunction;
1571 // Make sure that we keep track of the linkage type even if there was a
1572 // previous "declare".
1575 // Resolve circular types before we parse the body of the function.
1576 ResolveTypes(CurFun.LateResolveTypes);
1579 END : ENDTOK | '}'; // Allow end of '}' to end a function
1581 Function : BasicBlockList END {
1585 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1586 $$ = CurFun.CurrentFunction;
1587 CurFun.FunctionDone();
1590 //===----------------------------------------------------------------------===//
1591 // Rules to match Basic Blocks
1592 //===----------------------------------------------------------------------===//
1594 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1595 $$ = ValID::create($1);
1598 $$ = ValID::create($1);
1600 | FPVAL { // Perhaps it's an FP constant?
1601 $$ = ValID::create($1);
1604 $$ = ValID::create(ConstantBool::True);
1607 $$ = ValID::create(ConstantBool::False);
1610 $$ = ValID::createNull();
1613 $$ = ValID::create($1);
1616 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1619 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1620 $$ = ValID::create($1);
1622 | Name { // Is it a named reference...?
1623 $$ = ValID::create($1);
1626 // ValueRef - A reference to a definition... either constant or symbolic
1627 ValueRef : SymbolicValueRef | ConstValueRef;
1630 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1631 // type immediately preceeds the value reference, and allows complex constant
1632 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1633 ResolvedVal : Types ValueRef {
1634 $$ = getVal(*$1, $2); delete $1;
1637 BasicBlockList : BasicBlockList BasicBlock {
1638 ($$ = $1)->getBasicBlockList().push_back($2);
1640 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1641 ($$ = $1)->getBasicBlockList().push_back($2);
1645 // Basic blocks are terminated by branching instructions:
1646 // br, br/cc, switch, ret
1648 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1649 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1652 $1->getInstList().push_back($3);
1656 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1657 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1660 $2->getInstList().push_back($4);
1661 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1667 InstructionList : InstructionList Inst {
1668 $1->getInstList().push_back($2);
1672 $$ = CurBB = new BasicBlock();
1675 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1676 $$ = new ReturnInst($2);
1678 | RET VOID { // Return with no result...
1679 $$ = new ReturnInst();
1681 | BR LABEL ValueRef { // Unconditional Branch...
1682 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1683 } // Conditional Branch...
1684 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1685 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1686 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1687 getVal(Type::BoolTy, $3));
1689 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1690 SwitchInst *S = new SwitchInst(getVal($2, $3),
1691 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1694 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1697 S->addCase(I->first, I->second);
1700 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1701 SwitchInst *S = new SwitchInst(getVal($2, $3),
1702 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1705 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1706 UNWIND ResolvedVal {
1707 const PointerType *PFTy;
1708 const FunctionType *Ty;
1710 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1711 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1712 // Pull out the types of all of the arguments...
1713 std::vector<const Type*> ParamTypes;
1715 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1717 ParamTypes.push_back((*I)->getType());
1720 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1721 if (isVarArg) ParamTypes.pop_back();
1723 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1724 PFTy = PointerType::get(Ty);
1727 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1729 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1730 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1732 if (Normal == 0 || Except == 0)
1733 ThrowException("Invoke instruction without label destinations!");
1735 // Create the call node...
1736 if (!$5) { // Has no arguments?
1737 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1738 } else { // Has arguments?
1739 // Loop through FunctionType's arguments and ensure they are specified
1742 FunctionType::param_iterator I = Ty->param_begin();
1743 FunctionType::param_iterator E = Ty->param_end();
1744 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1746 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1747 if ((*ArgI)->getType() != *I)
1748 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1749 (*I)->getDescription() + "'!");
1751 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1752 ThrowException("Invalid number of parameters detected!");
1754 $$ = new InvokeInst(V, Normal, Except, *$5);
1760 $$ = new UnwindInst();
1765 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1767 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1769 ThrowException("May only switch on a constant pool value!");
1771 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1773 | IntType ConstValueRef ',' LABEL ValueRef {
1774 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1775 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1778 ThrowException("May only switch on a constant pool value!");
1780 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1783 Inst : OptAssign InstVal {
1784 // Is this definition named?? if so, assign the name...
1785 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1790 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1791 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1792 $$->push_back(std::make_pair(getVal(*$1, $3),
1793 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1796 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1798 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1799 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1803 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1804 $$ = new std::vector<Value*>();
1807 | ValueRefList ',' ResolvedVal {
1812 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1813 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1815 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1816 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1817 ThrowException("Arithmetic operator requires integer or FP operands!");
1818 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1820 ThrowException("binary operator returned null!");
1823 | LogicalOps Types ValueRef ',' ValueRef {
1824 if (!(*$2)->isIntegral())
1825 ThrowException("Logical operator requires integral operands!");
1826 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1828 ThrowException("binary operator returned null!");
1831 | SetCondOps Types ValueRef ',' ValueRef {
1832 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1834 ThrowException("binary operator returned null!");
1838 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1839 << " Replacing with 'xor'.\n";
1841 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1843 ThrowException("Expected integral type for not instruction!");
1845 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1847 ThrowException("Could not create a xor instruction!");
1849 | ShiftOps ResolvedVal ',' ResolvedVal {
1850 if ($4->getType() != Type::UByteTy)
1851 ThrowException("Shift amount must be ubyte!");
1852 if (!$2->getType()->isInteger())
1853 ThrowException("Shift constant expression requires integer operand!");
1854 $$ = new ShiftInst($1, $2, $4);
1856 | CAST ResolvedVal TO Types {
1857 if (!$4->get()->isFirstClassType())
1858 ThrowException("cast instruction to a non-primitive type: '" +
1859 $4->get()->getDescription() + "'!");
1860 $$ = new CastInst($2, *$4);
1863 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1864 if ($2->getType() != Type::BoolTy)
1865 ThrowException("select condition must be boolean!");
1866 if ($4->getType() != $6->getType())
1867 ThrowException("select value types should match!");
1868 $$ = new SelectInst($2, $4, $6);
1870 | VA_ARG ResolvedVal ',' Types {
1871 // FIXME: This is emulation code for an obsolete syntax. This should be
1872 // removed at some point.
1873 if (!ObsoleteVarArgs) {
1874 std::cerr << "WARNING: this file uses obsolete features. "
1875 << "Assemble and disassemble to update it.\n";
1876 ObsoleteVarArgs = true;
1879 // First, load the valist...
1880 Instruction *CurVAList = new LoadInst($2, "");
1881 CurBB->getInstList().push_back(CurVAList);
1883 // Emit the vaarg instruction.
1884 $$ = new VAArgInst(CurVAList, *$4);
1886 // Now we must advance the pointer and update it in memory.
1887 Instruction *TheVANext = new VANextInst(CurVAList, *$4);
1888 CurBB->getInstList().push_back(TheVANext);
1890 CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
1893 | VAARG ResolvedVal ',' Types {
1894 $$ = new VAArgInst($2, *$4);
1897 | VANEXT ResolvedVal ',' Types {
1898 $$ = new VANextInst($2, *$4);
1902 const Type *Ty = $2->front().first->getType();
1903 if (!Ty->isFirstClassType())
1904 ThrowException("PHI node operands must be of first class type!");
1905 $$ = new PHINode(Ty);
1906 $$->op_reserve($2->size()*2);
1907 while ($2->begin() != $2->end()) {
1908 if ($2->front().first->getType() != Ty)
1909 ThrowException("All elements of a PHI node must be of the same type!");
1910 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1913 delete $2; // Free the list...
1915 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1916 const PointerType *PFTy;
1917 const FunctionType *Ty;
1919 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1920 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1921 // Pull out the types of all of the arguments...
1922 std::vector<const Type*> ParamTypes;
1924 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1926 ParamTypes.push_back((*I)->getType());
1929 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1930 if (isVarArg) ParamTypes.pop_back();
1932 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1933 PFTy = PointerType::get(Ty);
1936 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1938 // Create the call node...
1939 if (!$5) { // Has no arguments?
1940 // Make sure no arguments is a good thing!
1941 if (Ty->getNumParams() != 0)
1942 ThrowException("No arguments passed to a function that "
1943 "expects arguments!");
1945 $$ = new CallInst(V, std::vector<Value*>());
1946 } else { // Has arguments?
1947 // Loop through FunctionType's arguments and ensure they are specified
1950 FunctionType::param_iterator I = Ty->param_begin();
1951 FunctionType::param_iterator E = Ty->param_end();
1952 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1954 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1955 if ((*ArgI)->getType() != *I)
1956 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1957 (*I)->getDescription() + "'!");
1959 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1960 ThrowException("Invalid number of parameters detected!");
1962 $$ = new CallInst(V, *$5);
1972 // IndexList - List of indices for GEP based instructions...
1973 IndexList : ',' ValueRefList {
1976 $$ = new std::vector<Value*>();
1979 OptVolatile : VOLATILE {
1987 MemoryInst : MALLOC Types {
1988 $$ = new MallocInst(*$2);
1991 | MALLOC Types ',' UINT ValueRef {
1992 $$ = new MallocInst(*$2, getVal($4, $5));
1996 $$ = new AllocaInst(*$2);
1999 | ALLOCA Types ',' UINT ValueRef {
2000 $$ = new AllocaInst(*$2, getVal($4, $5));
2003 | FREE ResolvedVal {
2004 if (!isa<PointerType>($2->getType()))
2005 ThrowException("Trying to free nonpointer type " +
2006 $2->getType()->getDescription() + "!");
2007 $$ = new FreeInst($2);
2010 | OptVolatile LOAD Types ValueRef {
2011 if (!isa<PointerType>($3->get()))
2012 ThrowException("Can't load from nonpointer type: " +
2013 (*$3)->getDescription());
2014 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2017 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2018 const PointerType *PT = dyn_cast<PointerType>($5->get());
2020 ThrowException("Can't store to a nonpointer type: " +
2021 (*$5)->getDescription());
2022 const Type *ElTy = PT->getElementType();
2023 if (ElTy != $3->getType())
2024 ThrowException("Can't store '" + $3->getType()->getDescription() +
2025 "' into space of type '" + ElTy->getDescription() + "'!");
2027 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2030 | GETELEMENTPTR Types ValueRef IndexList {
2031 if (!isa<PointerType>($2->get()))
2032 ThrowException("getelementptr insn requires pointer operand!");
2034 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2035 // indices to uint struct indices for compatibility.
2036 generic_gep_type_iterator<std::vector<Value*>::iterator>
2037 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2038 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2039 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2040 if (isa<StructType>(*GTI)) // Only change struct indices
2041 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2042 if (CUI->getType() == Type::UByteTy)
2043 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2045 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2046 ThrowException("Invalid getelementptr indices for type '" +
2047 (*$2)->getDescription()+ "'!");
2048 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2049 delete $2; delete $4;
2054 int yyerror(const char *ErrorMsg) {
2056 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2057 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2058 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2059 if (yychar == YYEMPTY || yychar == 0)
2060 errMsg += "end-of-file.";
2062 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2063 ThrowException(errMsg);