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::map<unsigned,ValueList> &LateResolvers,
61 std::map<unsigned,ValueList> *FutureLateResolvers = 0);
63 static struct PerModuleInfo {
64 Module *CurrentModule;
65 std::map<unsigned,ValueList> Values; // Module level numbered definitions
66 std::map<unsigned,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>, GlobalValue*> 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 GlobalValue *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->replaceUsesOfWithOnConstant(OldGV, GV);
129 assert(OldGV->use_empty() && "All uses should be gone now!");
131 // Remove OldGV from the module...
132 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(OldGV))
133 CurrentModule->getGlobalList().erase(GVar);
135 CurrentModule->getFunctionList().erase(cast<Function>(OldGV));
137 // Remove the map entry for the global now that it has been created...
144 static struct PerFunctionInfo {
145 Function *CurrentFunction; // Pointer to current function being created
147 std::map<unsigned,ValueList> Values; // Keep track of numbered definitions
148 std::map<unsigned,ValueList> LateResolveValues;
149 std::vector<PATypeHolder> Types;
150 std::map<ValID, PATypeHolder> LateResolveTypes;
151 SymbolTable LocalSymtab;
152 bool isDeclare; // Is this function a forward declararation?
154 inline PerFunctionInfo() {
159 inline void FunctionStart(Function *M) {
163 void FunctionDone() {
164 // If we could not resolve some blocks at parsing time (forward branches)
165 // resolve the branches now...
166 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
168 // Make sure to resolve any constant expr references that might exist within
169 // the function we just declared itself.
171 if (CurrentFunction->hasName()) {
172 FID = ValID::create((char*)CurrentFunction->getName().c_str());
174 unsigned Slot = CurrentFunction->getType()->getUniqueID();
175 // Figure out which slot number if is...
176 ValueList &List = CurModule.Values[Slot];
177 for (unsigned i = 0; ; ++i) {
178 assert(i < List.size() && "Function not found!");
179 if (List[i] == CurrentFunction) {
180 FID = ValID::create((int)i);
185 CurModule.DeclareNewGlobalValue(CurrentFunction, FID);
187 Values.clear(); // Clear out function local definitions
188 Types.clear(); // Clear out function local types
189 LocalSymtab.clear(); // Clear out function local symbol table
193 } CurFun; // Info for the current function...
195 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
198 //===----------------------------------------------------------------------===//
199 // Code to handle definitions of all the types
200 //===----------------------------------------------------------------------===//
202 static int InsertValue(Value *D,
203 std::map<unsigned,ValueList> &ValueTab = CurFun.Values) {
204 if (D->hasName()) return -1; // Is this a numbered definition?
206 // Yes, insert the value into the value table...
207 unsigned type = D->getType()->getUniqueID();
208 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
209 ValueList &List = ValueTab[type];
211 return List.size()-1;
214 // TODO: FIXME when Type are not const
215 static void InsertType(const Type *Ty, std::vector<PATypeHolder> &Types) {
219 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
221 case ValID::NumberVal: { // Is it a numbered definition?
222 unsigned Num = (unsigned)D.Num;
224 // Module constants occupy the lowest numbered slots...
225 if (Num < CurModule.Types.size())
226 return CurModule.Types[Num];
228 Num -= CurModule.Types.size();
230 // Check that the number is within bounds...
231 if (Num <= CurFun.Types.size())
232 return CurFun.Types[Num];
235 case ValID::NameVal: { // Is it a named definition?
236 std::string Name(D.Name);
237 SymbolTable *SymTab = 0;
239 if (inFunctionScope()) {
240 SymTab = &CurFun.CurrentFunction->getSymbolTable();
241 N = SymTab->lookup(Type::TypeTy, Name);
245 // Symbol table doesn't automatically chain yet... because the function
246 // hasn't been added to the module...
248 SymTab = &CurModule.CurrentModule->getSymbolTable();
249 N = SymTab->lookup(Type::TypeTy, Name);
253 D.destroy(); // Free old strdup'd memory...
254 return cast<Type>(N);
257 ThrowException("Internal parser error: Invalid symbol type reference!");
260 // If we reached here, we referenced either a symbol that we don't know about
261 // or an id number that hasn't been read yet. We may be referencing something
262 // forward, so just create an entry to be resolved later and get to it...
264 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
266 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
267 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
269 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
270 if (I != LateResolver.end()) {
274 Type *Typ = OpaqueType::get();
275 LateResolver.insert(std::make_pair(D, Typ));
279 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
280 SymbolTable &SymTab =
281 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
282 CurModule.CurrentModule->getSymbolTable();
283 return SymTab.lookup(Ty, Name);
286 // getValNonImprovising - Look up the value specified by the provided type and
287 // the provided ValID. If the value exists and has already been defined, return
288 // it. Otherwise return null.
290 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
291 if (isa<FunctionType>(Ty))
292 ThrowException("Functions are not values and "
293 "must be referenced as pointers");
296 case ValID::NumberVal: { // Is it a numbered definition?
297 unsigned type = Ty->getUniqueID();
298 unsigned Num = (unsigned)D.Num;
300 // Module constants occupy the lowest numbered slots...
301 std::map<unsigned,ValueList>::iterator VI = CurModule.Values.find(type);
302 if (VI != CurModule.Values.end()) {
303 if (Num < VI->second.size())
304 return VI->second[Num];
305 Num -= VI->second.size();
308 // Make sure that our type is within bounds
309 VI = CurFun.Values.find(type);
310 if (VI == CurFun.Values.end()) return 0;
312 // Check that the number is within bounds...
313 if (VI->second.size() <= Num) return 0;
315 return VI->second[Num];
318 case ValID::NameVal: { // Is it a named definition?
319 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
320 if (N == 0) return 0;
322 D.destroy(); // Free old strdup'd memory...
326 // Check to make sure that "Ty" is an integral type, and that our
327 // value will fit into the specified type...
328 case ValID::ConstSIntVal: // Is it a constant pool reference??
329 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
330 ThrowException("Signed integral constant '" +
331 itostr(D.ConstPool64) + "' is invalid for type '" +
332 Ty->getDescription() + "'!");
333 return ConstantSInt::get(Ty, D.ConstPool64);
335 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
336 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
337 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
338 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
339 "' is invalid or out of range!");
340 } else { // This is really a signed reference. Transmogrify.
341 return ConstantSInt::get(Ty, D.ConstPool64);
344 return ConstantUInt::get(Ty, D.UConstPool64);
347 case ValID::ConstFPVal: // Is it a floating point const pool reference?
348 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
349 ThrowException("FP constant invalid for type!!");
350 return ConstantFP::get(Ty, D.ConstPoolFP);
352 case ValID::ConstNullVal: // Is it a null value?
353 if (!isa<PointerType>(Ty))
354 ThrowException("Cannot create a a non pointer null!");
355 return ConstantPointerNull::get(cast<PointerType>(Ty));
357 case ValID::ConstantVal: // Fully resolved constant?
358 if (D.ConstantValue->getType() != Ty)
359 ThrowException("Constant expression type different from required type!");
360 return D.ConstantValue;
363 assert(0 && "Unhandled case!");
367 assert(0 && "Unhandled case!");
372 // getVal - This function is identical to getValNonImprovising, except that if a
373 // value is not already defined, it "improvises" by creating a placeholder var
374 // that looks and acts just like the requested variable. When the value is
375 // defined later, all uses of the placeholder variable are replaced with the
378 static Value *getVal(const Type *Ty, const ValID &D) {
379 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
381 // See if the value has already been defined...
382 Value *V = getValNonImprovising(Ty, D);
385 // If we reached here, we referenced either a symbol that we don't know about
386 // or an id number that hasn't been read yet. We may be referencing something
387 // forward, so just create an entry to be resolved later and get to it...
390 switch (Ty->getPrimitiveID()) {
391 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
392 default: d = new ValuePlaceHolder(Ty, D); break;
395 assert(d != 0 && "How did we not make something?");
396 if (inFunctionScope())
397 InsertValue(d, CurFun.LateResolveValues);
399 InsertValue(d, CurModule.LateResolveValues);
404 //===----------------------------------------------------------------------===//
405 // Code to handle forward references in instructions
406 //===----------------------------------------------------------------------===//
408 // This code handles the late binding needed with statements that reference
409 // values not defined yet... for example, a forward branch, or the PHI node for
412 // This keeps a table (CurFun.LateResolveValues) of all such forward references
413 // and back patchs after we are done.
416 // ResolveDefinitions - If we could not resolve some defs at parsing
417 // time (forward branches, phi functions for loops, etc...) resolve the
420 static void ResolveDefinitions(std::map<unsigned,ValueList> &LateResolvers,
421 std::map<unsigned,ValueList> *FutureLateResolvers) {
422 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
423 for (std::map<unsigned,ValueList>::iterator LRI = LateResolvers.begin(),
424 E = LateResolvers.end(); LRI != E; ++LRI) {
425 ValueList &List = LRI->second;
426 while (!List.empty()) {
427 Value *V = List.back();
429 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
430 ValID &DID = getValIDFromPlaceHolder(V);
432 Value *TheRealValue =
433 getValNonImprovising(Type::getUniqueIDType(LRI->first), DID);
435 V->replaceAllUsesWith(TheRealValue);
437 } else if (FutureLateResolvers) {
438 // Functions have their unresolved items forwarded to the module late
440 InsertValue(V, *FutureLateResolvers);
442 if (DID.Type == ValID::NameVal)
443 ThrowException("Reference to an invalid definition: '" +DID.getName()+
444 "' of type '" + V->getType()->getDescription() + "'",
445 getLineNumFromPlaceHolder(V));
447 ThrowException("Reference to an invalid definition: #" +
448 itostr(DID.Num) + " of type '" +
449 V->getType()->getDescription() + "'",
450 getLineNumFromPlaceHolder(V));
455 LateResolvers.clear();
458 // ResolveTypeTo - A brand new type was just declared. This means that (if
459 // name is not null) things referencing Name can be resolved. Otherwise, things
460 // refering to the number can be resolved. Do this now.
462 static void ResolveTypeTo(char *Name, const Type *ToTy) {
463 std::vector<PATypeHolder> &Types = inFunctionScope() ?
464 CurFun.Types : CurModule.Types;
467 if (Name) D = ValID::create(Name);
468 else D = ValID::create((int)Types.size());
470 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
471 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
473 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
474 if (I != LateResolver.end()) {
475 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
476 LateResolver.erase(I);
480 // ResolveTypes - At this point, all types should be resolved. Any that aren't
483 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
484 if (!LateResolveTypes.empty()) {
485 const ValID &DID = LateResolveTypes.begin()->first;
487 if (DID.Type == ValID::NameVal)
488 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
490 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
495 // setValueName - Set the specified value to the name given. The name may be
496 // null potentially, in which case this is a noop. The string passed in is
497 // assumed to be a malloc'd string buffer, and is freed by this function.
499 // This function returns true if the value has already been defined, but is
500 // allowed to be redefined in the specified context. If the name is a new name
501 // for the typeplane, false is returned.
503 static bool setValueName(Value *V, char *NameStr) {
504 if (NameStr == 0) return false;
506 std::string Name(NameStr); // Copy string
507 free(NameStr); // Free old string
509 if (V->getType() == Type::VoidTy)
510 ThrowException("Can't assign name '" + Name +
511 "' to a null valued instruction!");
513 SymbolTable &ST = inFunctionScope() ?
514 CurFun.CurrentFunction->getSymbolTable() :
515 CurModule.CurrentModule->getSymbolTable();
517 Value *Existing = ST.lookup(V->getType(), Name);
518 if (Existing) { // Inserting a name that is already defined???
519 // There is only one case where this is allowed: when we are refining an
520 // opaque type. In this case, Existing will be an opaque type.
521 if (const Type *Ty = dyn_cast<Type>(Existing)) {
522 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
523 // We ARE replacing an opaque type!
524 ((OpaqueType*)OpTy)->refineAbstractTypeTo(cast<Type>(V));
529 // Otherwise, we are a simple redefinition of a value, check to see if it
530 // is defined the same as the old one...
531 if (const Type *Ty = dyn_cast<Type>(Existing)) {
532 if (Ty == cast<Type>(V)) return true; // Yes, it's equal.
533 // std::cerr << "Type: " << Ty->getDescription() << " != "
534 // << cast<Type>(V)->getDescription() << "!\n";
535 } else if (const Constant *C = dyn_cast<Constant>(Existing)) {
536 if (C == V) return true; // Constants are equal to themselves
537 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
538 // We are allowed to redefine a global variable in two circumstances:
539 // 1. If at least one of the globals is uninitialized or
540 // 2. If both initializers have the same value.
542 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
543 if (!EGV->hasInitializer() || !GV->hasInitializer() ||
544 EGV->getInitializer() == GV->getInitializer()) {
546 // Make sure the existing global version gets the initializer! Make
547 // sure that it also gets marked const if the new version is.
548 if (GV->hasInitializer() && !EGV->hasInitializer())
549 EGV->setInitializer(GV->getInitializer());
550 if (GV->isConstant())
551 EGV->setConstant(true);
552 EGV->setLinkage(GV->getLinkage());
554 delete GV; // Destroy the duplicate!
555 return true; // They are equivalent!
560 ThrowException("Redefinition of value named '" + Name + "' in the '" +
561 V->getType()->getDescription() + "' type plane!");
565 V->setName(Name, &ST);
567 // If we're in function scope
568 if (inFunctionScope()) {
569 // Look up the symbol in the function's local symboltable
570 Existing = CurFun.LocalSymtab.lookup(V->getType(),Name);
572 // If it already exists
575 ThrowException("Redefinition of value named '" + Name + "' in the '" +
576 V->getType()->getDescription() + "' type plane!");
578 // otherwise, since it doesn't exist
581 CurFun.LocalSymtab.insert(V);
588 //===----------------------------------------------------------------------===//
589 // Code for handling upreferences in type names...
592 // TypeContains - Returns true if Ty directly contains E in it.
594 static bool TypeContains(const Type *Ty, const Type *E) {
595 return find(Ty->subtype_begin(), Ty->subtype_end(), E) != Ty->subtype_end();
600 // NestingLevel - The number of nesting levels that need to be popped before
601 // this type is resolved.
602 unsigned NestingLevel;
604 // LastContainedTy - This is the type at the current binding level for the
605 // type. Every time we reduce the nesting level, this gets updated.
606 const Type *LastContainedTy;
608 // UpRefTy - This is the actual opaque type that the upreference is
612 UpRefRecord(unsigned NL, OpaqueType *URTy)
613 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
617 // UpRefs - A list of the outstanding upreferences that need to be resolved.
618 static std::vector<UpRefRecord> UpRefs;
620 /// HandleUpRefs - Every time we finish a new layer of types, this function is
621 /// called. It loops through the UpRefs vector, which is a list of the
622 /// currently active types. For each type, if the up reference is contained in
623 /// the newly completed type, we decrement the level count. When the level
624 /// count reaches zero, the upreferenced type is the type that is passed in:
625 /// thus we can complete the cycle.
627 static PATypeHolder HandleUpRefs(const Type *ty) {
628 if (!ty->isAbstract()) return ty;
630 UR_OUT("Type '" << Ty->getDescription() <<
631 "' newly formed. Resolving upreferences.\n" <<
632 UpRefs.size() << " upreferences active!\n");
634 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
635 // to zero), we resolve them all together before we resolve them to Ty. At
636 // the end of the loop, if there is anything to resolve to Ty, it will be in
638 OpaqueType *TypeToResolve = 0;
640 for (unsigned i = 0; i != UpRefs.size(); ++i) {
641 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
642 << UpRefs[i].second->getDescription() << ") = "
643 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
644 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
645 // Decrement level of upreference
646 unsigned Level = --UpRefs[i].NestingLevel;
647 UpRefs[i].LastContainedTy = Ty;
648 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
649 if (Level == 0) { // Upreference should be resolved!
650 if (!TypeToResolve) {
651 TypeToResolve = UpRefs[i].UpRefTy;
653 UR_OUT(" * Resolving upreference for "
654 << UpRefs[i].second->getDescription() << "\n";
655 std::string OldName = UpRefs[i].UpRefTy->getDescription());
656 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
657 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
658 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
660 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
661 --i; // Do not skip the next element...
667 UR_OUT(" * Resolving upreference for "
668 << UpRefs[i].second->getDescription() << "\n";
669 std::string OldName = TypeToResolve->getDescription());
670 TypeToResolve->refineAbstractTypeTo(Ty);
677 //===----------------------------------------------------------------------===//
678 // RunVMAsmParser - Define an interface to this parser
679 //===----------------------------------------------------------------------===//
681 Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
683 CurFilename = Filename;
684 llvmAsmlineno = 1; // Reset the current line number...
685 ObsoleteVarArgs = false;
687 // Allocate a new module to read
688 CurModule.CurrentModule = new Module(Filename);
691 yyparse(); // Parse the file.
693 // Clear the symbol table so it doesn't complain when it
695 CurFun.LocalSymtab.clear();
699 Module *Result = ParserResult;
701 // Check to see if they called va_start but not va_arg..
702 if (!ObsoleteVarArgs)
703 if (Function *F = Result->getNamedFunction("llvm.va_start"))
704 if (F->asize() == 1) {
705 std::cerr << "WARNING: this file uses obsolete features. "
706 << "Assemble and disassemble to update it.\n";
707 ObsoleteVarArgs = true;
711 if (ObsoleteVarArgs) {
712 // If the user is making use of obsolete varargs intrinsics, adjust them for
714 if (Function *F = Result->getNamedFunction("llvm.va_start")) {
715 assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
717 const Type *RetTy = F->getFunctionType()->getParamType(0);
718 RetTy = cast<PointerType>(RetTy)->getElementType();
719 Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
721 while (!F->use_empty()) {
722 CallInst *CI = cast<CallInst>(F->use_back());
723 Value *V = new CallInst(NF, "", CI);
724 new StoreInst(V, CI->getOperand(1), CI);
725 CI->getParent()->getInstList().erase(CI);
727 Result->getFunctionList().erase(F);
730 if (Function *F = Result->getNamedFunction("llvm.va_end")) {
731 assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
732 const Type *ArgTy = F->getFunctionType()->getParamType(0);
733 ArgTy = cast<PointerType>(ArgTy)->getElementType();
734 Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
737 while (!F->use_empty()) {
738 CallInst *CI = cast<CallInst>(F->use_back());
739 Value *V = new LoadInst(CI->getOperand(1), "", CI);
740 new CallInst(NF, V, "", CI);
741 CI->getParent()->getInstList().erase(CI);
743 Result->getFunctionList().erase(F);
746 if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
747 assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
748 const Type *ArgTy = F->getFunctionType()->getParamType(0);
749 ArgTy = cast<PointerType>(ArgTy)->getElementType();
750 Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
753 while (!F->use_empty()) {
754 CallInst *CI = cast<CallInst>(F->use_back());
755 Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
756 new StoreInst(V, CI->getOperand(1), CI);
757 CI->getParent()->getInstList().erase(CI);
759 Result->getFunctionList().erase(F);
763 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
769 } // End llvm namespace
771 using namespace llvm;
776 llvm::Module *ModuleVal;
777 llvm::Function *FunctionVal;
778 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
779 llvm::BasicBlock *BasicBlockVal;
780 llvm::TerminatorInst *TermInstVal;
781 llvm::Instruction *InstVal;
782 llvm::Constant *ConstVal;
784 const llvm::Type *PrimType;
785 llvm::PATypeHolder *TypeVal;
786 llvm::Value *ValueVal;
788 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
789 std::vector<llvm::Value*> *ValueList;
790 std::list<llvm::PATypeHolder> *TypeList;
791 std::list<std::pair<llvm::Value*,
792 llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
793 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
794 std::vector<llvm::Constant*> *ConstVector;
796 llvm::GlobalValue::LinkageTypes Linkage;
804 char *StrVal; // This memory is strdup'd!
805 llvm::ValID ValIDVal; // strdup'd memory maybe!
807 llvm::Instruction::BinaryOps BinaryOpVal;
808 llvm::Instruction::TermOps TermOpVal;
809 llvm::Instruction::MemoryOps MemOpVal;
810 llvm::Instruction::OtherOps OtherOpVal;
811 llvm::Module::Endianness Endianness;
814 %type <ModuleVal> Module FunctionList
815 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
816 %type <BasicBlockVal> BasicBlock InstructionList
817 %type <TermInstVal> BBTerminatorInst
818 %type <InstVal> Inst InstVal MemoryInst
819 %type <ConstVal> ConstVal ConstExpr
820 %type <ConstVector> ConstVector
821 %type <ArgList> ArgList ArgListH
822 %type <ArgVal> ArgVal
823 %type <PHIList> PHIList
824 %type <ValueList> ValueRefList ValueRefListE // For call param lists
825 %type <ValueList> IndexList // For GEP derived indices
826 %type <TypeList> TypeListI ArgTypeListI
827 %type <JumpTable> JumpTable
828 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
829 %type <BoolVal> OptVolatile // 'volatile' or not
830 %type <Linkage> OptLinkage
831 %type <Endianness> BigOrLittle
833 // ValueRef - Unresolved reference to a definition or BB
834 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
835 %type <ValueVal> ResolvedVal // <type> <valref> pair
836 // Tokens and types for handling constant integer values
838 // ESINT64VAL - A negative number within long long range
839 %token <SInt64Val> ESINT64VAL
841 // EUINT64VAL - A positive number within uns. long long range
842 %token <UInt64Val> EUINT64VAL
843 %type <SInt64Val> EINT64VAL
845 %token <SIntVal> SINTVAL // Signed 32 bit ints...
846 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
847 %type <SIntVal> INTVAL
848 %token <FPVal> FPVAL // Float or Double constant
851 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
852 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
853 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
854 %token <PrimType> FLOAT DOUBLE TYPE LABEL
856 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
857 %type <StrVal> Name OptName OptAssign
860 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
861 %token DECLARE GLOBAL CONSTANT VOLATILE
862 %token TO DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE WEAK APPENDING
863 %token OPAQUE NOT EXTERNAL TARGET ENDIAN POINTERSIZE LITTLE BIG
865 // Basic Block Terminating Operators
866 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND
869 %type <BinaryOpVal> BinaryOps // all the binary operators
870 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
871 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
872 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
874 // Memory Instructions
875 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
878 %type <OtherOpVal> ShiftOps
879 %token <OtherOpVal> PHI_TOK CALL CAST SELECT SHL SHR VAARG VANEXT
880 %token VA_ARG // FIXME: OBSOLETE
885 // Handle constant integer size restriction and conversion...
889 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
890 ThrowException("Value too large for type!");
895 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
896 EINT64VAL : EUINT64VAL {
897 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
898 ThrowException("Value too large for type!");
902 // Operations that are notably excluded from this list include:
903 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
905 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
906 LogicalOps : AND | OR | XOR;
907 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
908 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
910 ShiftOps : SHL | SHR;
912 // These are some types that allow classification if we only want a particular
913 // thing... for example, only a signed, unsigned, or integral type.
914 SIntType : LONG | INT | SHORT | SBYTE;
915 UIntType : ULONG | UINT | USHORT | UBYTE;
916 IntType : SIntType | UIntType;
917 FPType : FLOAT | DOUBLE;
919 // OptAssign - Value producing statements have an optional assignment component
920 OptAssign : Name '=' {
927 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
928 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
929 WEAK { $$ = GlobalValue::WeakLinkage; } |
930 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
931 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
933 //===----------------------------------------------------------------------===//
934 // Types includes all predefined types... except void, because it can only be
935 // used in specific contexts (function returning void for example). To have
936 // access to it, a user must explicitly use TypesV.
939 // TypesV includes all of 'Types', but it also includes the void type.
940 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
941 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
945 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
950 // Derived types are added later...
952 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
953 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
955 $$ = new PATypeHolder(OpaqueType::get());
958 $$ = new PATypeHolder($1);
960 UpRTypes : SymbolicValueRef { // Named types are also simple types...
961 $$ = new PATypeHolder(getTypeVal($1));
964 // Include derived types in the Types production.
966 UpRTypes : '\\' EUINT64VAL { // Type UpReference
967 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
968 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
969 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
970 $$ = new PATypeHolder(OT);
971 UR_OUT("New Upreference!\n");
973 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
974 std::vector<const Type*> Params;
975 mapto($3->begin(), $3->end(), std::back_inserter(Params),
976 std::mem_fun_ref(&PATypeHolder::get));
977 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
978 if (isVarArg) Params.pop_back();
980 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
981 delete $3; // Delete the argument list
982 delete $1; // Delete the return type handle
984 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
985 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
988 | '{' TypeListI '}' { // Structure type?
989 std::vector<const Type*> Elements;
990 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
991 std::mem_fun_ref(&PATypeHolder::get));
993 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
996 | '{' '}' { // Empty structure type?
997 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
999 | UpRTypes '*' { // Pointer type?
1000 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1004 // TypeList - Used for struct declarations and as a basis for function type
1005 // declaration type lists
1007 TypeListI : UpRTypes {
1008 $$ = new std::list<PATypeHolder>();
1009 $$->push_back(*$1); delete $1;
1011 | TypeListI ',' UpRTypes {
1012 ($$=$1)->push_back(*$3); delete $3;
1015 // ArgTypeList - List of types for a function type declaration...
1016 ArgTypeListI : TypeListI
1017 | TypeListI ',' DOTDOTDOT {
1018 ($$=$1)->push_back(Type::VoidTy);
1021 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1024 $$ = new std::list<PATypeHolder>();
1027 // ConstVal - The various declarations that go into the constant pool. This
1028 // production is used ONLY to represent constants that show up AFTER a 'const',
1029 // 'constant' or 'global' token at global scope. Constants that can be inlined
1030 // into other expressions (such as integers and constexprs) are handled by the
1031 // ResolvedVal, ValueRef and ConstValueRef productions.
1033 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1034 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1036 ThrowException("Cannot make array constant with type: '" +
1037 (*$1)->getDescription() + "'!");
1038 const Type *ETy = ATy->getElementType();
1039 int NumElements = ATy->getNumElements();
1041 // Verify that we have the correct size...
1042 if (NumElements != -1 && NumElements != (int)$3->size())
1043 ThrowException("Type mismatch: constant sized array initialized with " +
1044 utostr($3->size()) + " arguments, but has size of " +
1045 itostr(NumElements) + "!");
1047 // Verify all elements are correct type!
1048 for (unsigned i = 0; i < $3->size(); i++) {
1049 if (ETy != (*$3)[i]->getType())
1050 ThrowException("Element #" + utostr(i) + " is not of type '" +
1051 ETy->getDescription() +"' as required!\nIt is of type '"+
1052 (*$3)[i]->getType()->getDescription() + "'.");
1055 $$ = ConstantArray::get(ATy, *$3);
1056 delete $1; delete $3;
1059 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1061 ThrowException("Cannot make array constant with type: '" +
1062 (*$1)->getDescription() + "'!");
1064 int NumElements = ATy->getNumElements();
1065 if (NumElements != -1 && NumElements != 0)
1066 ThrowException("Type mismatch: constant sized array initialized with 0"
1067 " arguments, but has size of " + itostr(NumElements) +"!");
1068 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1071 | Types 'c' STRINGCONSTANT {
1072 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1074 ThrowException("Cannot make array constant with type: '" +
1075 (*$1)->getDescription() + "'!");
1077 int NumElements = ATy->getNumElements();
1078 const Type *ETy = ATy->getElementType();
1079 char *EndStr = UnEscapeLexed($3, true);
1080 if (NumElements != -1 && NumElements != (EndStr-$3))
1081 ThrowException("Can't build string constant of size " +
1082 itostr((int)(EndStr-$3)) +
1083 " when array has size " + itostr(NumElements) + "!");
1084 std::vector<Constant*> Vals;
1085 if (ETy == Type::SByteTy) {
1086 for (char *C = $3; C != EndStr; ++C)
1087 Vals.push_back(ConstantSInt::get(ETy, *C));
1088 } else if (ETy == Type::UByteTy) {
1089 for (char *C = $3; C != EndStr; ++C)
1090 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1093 ThrowException("Cannot build string arrays of non byte sized elements!");
1096 $$ = ConstantArray::get(ATy, Vals);
1099 | Types '{' ConstVector '}' {
1100 const StructType *STy = dyn_cast<StructType>($1->get());
1102 ThrowException("Cannot make struct constant with type: '" +
1103 (*$1)->getDescription() + "'!");
1105 if ($3->size() != STy->getNumContainedTypes())
1106 ThrowException("Illegal number of initializers for structure type!");
1108 // Check to ensure that constants are compatible with the type initializer!
1109 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1110 if ((*$3)[i]->getType() != STy->getElementType(i))
1111 ThrowException("Expected type '" +
1112 STy->getElementType(i)->getDescription() +
1113 "' for element #" + utostr(i) +
1114 " of structure initializer!");
1116 $$ = ConstantStruct::get(STy, *$3);
1117 delete $1; delete $3;
1120 const StructType *STy = dyn_cast<StructType>($1->get());
1122 ThrowException("Cannot make struct constant with type: '" +
1123 (*$1)->getDescription() + "'!");
1125 if (STy->getNumContainedTypes() != 0)
1126 ThrowException("Illegal number of initializers for structure type!");
1128 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1132 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1134 ThrowException("Cannot make null pointer constant with type: '" +
1135 (*$1)->getDescription() + "'!");
1137 $$ = ConstantPointerNull::get(PTy);
1140 | Types SymbolicValueRef {
1141 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1143 ThrowException("Global const reference must be a pointer type!");
1145 // ConstExprs can exist in the body of a function, thus creating
1146 // ConstantPointerRefs whenever they refer to a variable. Because we are in
1147 // the context of a function, getValNonImprovising will search the functions
1148 // symbol table instead of the module symbol table for the global symbol,
1149 // which throws things all off. To get around this, we just tell
1150 // getValNonImprovising that we are at global scope here.
1152 Function *SavedCurFn = CurFun.CurrentFunction;
1153 CurFun.CurrentFunction = 0;
1155 Value *V = getValNonImprovising(Ty, $2);
1157 CurFun.CurrentFunction = SavedCurFn;
1159 // If this is an initializer for a constant pointer, which is referencing a
1160 // (currently) undefined variable, create a stub now that shall be replaced
1161 // in the future with the right type of variable.
1164 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1165 const PointerType *PT = cast<PointerType>(Ty);
1167 // First check to see if the forward references value is already created!
1168 PerModuleInfo::GlobalRefsType::iterator I =
1169 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1171 if (I != CurModule.GlobalRefs.end()) {
1172 V = I->second; // Placeholder already exists, use it...
1175 // Create a placeholder for the global variable reference...
1176 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
1178 GlobalValue::ExternalLinkage);
1179 // Keep track of the fact that we have a forward ref to recycle it
1180 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1182 // Must temporarily push this value into the module table...
1183 CurModule.CurrentModule->getGlobalList().push_back(GV);
1188 GlobalValue *GV = cast<GlobalValue>(V);
1189 $$ = ConstantPointerRef::get(GV);
1190 delete $1; // Free the type handle
1193 if ($1->get() != $2->getType())
1194 ThrowException("Mismatched types for constant expression!");
1198 | Types ZEROINITIALIZER {
1199 $$ = Constant::getNullValue($1->get());
1203 ConstVal : SIntType EINT64VAL { // integral constants
1204 if (!ConstantSInt::isValueValidForType($1, $2))
1205 ThrowException("Constant value doesn't fit in type!");
1206 $$ = ConstantSInt::get($1, $2);
1208 | UIntType EUINT64VAL { // integral constants
1209 if (!ConstantUInt::isValueValidForType($1, $2))
1210 ThrowException("Constant value doesn't fit in type!");
1211 $$ = ConstantUInt::get($1, $2);
1213 | BOOL TRUETOK { // Boolean constants
1214 $$ = ConstantBool::True;
1216 | BOOL FALSETOK { // Boolean constants
1217 $$ = ConstantBool::False;
1219 | FPType FPVAL { // Float & Double constants
1220 $$ = ConstantFP::get($1, $2);
1224 ConstExpr: CAST '(' ConstVal TO Types ')' {
1225 if (!$3->getType()->isFirstClassType())
1226 ThrowException("cast constant expression from a non-primitive type: '" +
1227 $3->getType()->getDescription() + "'!");
1228 if (!$5->get()->isFirstClassType())
1229 ThrowException("cast constant expression to a non-primitive type: '" +
1230 $5->get()->getDescription() + "'!");
1231 $$ = ConstantExpr::getCast($3, $5->get());
1234 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1235 if (!isa<PointerType>($3->getType()))
1236 ThrowException("GetElementPtr requires a pointer operand!");
1239 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1241 ThrowException("Index list invalid for constant getelementptr!");
1243 std::vector<Constant*> IdxVec;
1244 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1245 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1246 IdxVec.push_back(C);
1248 ThrowException("Indices to constant getelementptr must be constants!");
1252 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1254 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1255 if ($3->getType() != Type::BoolTy)
1256 ThrowException("Select condition must be of boolean type!");
1257 if ($5->getType() != $7->getType())
1258 ThrowException("Select operand types must match!");
1259 $$ = ConstantExpr::getSelect($3, $5, $7);
1261 | BinaryOps '(' ConstVal ',' ConstVal ')' {
1262 if ($3->getType() != $5->getType())
1263 ThrowException("Binary operator types must match!");
1264 $$ = ConstantExpr::get($1, $3, $5);
1266 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1267 if ($5->getType() != Type::UByteTy)
1268 ThrowException("Shift count for shift constant must be unsigned byte!");
1269 if (!$3->getType()->isInteger())
1270 ThrowException("Shift constant expression requires integer operand!");
1271 $$ = ConstantExpr::get($1, $3, $5);
1275 // ConstVector - A list of comma separated constants.
1276 ConstVector : ConstVector ',' ConstVal {
1277 ($$ = $1)->push_back($3);
1280 $$ = new std::vector<Constant*>();
1285 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1286 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1289 //===----------------------------------------------------------------------===//
1290 // Rules to match Modules
1291 //===----------------------------------------------------------------------===//
1293 // Module rule: Capture the result of parsing the whole file into a result
1296 Module : FunctionList {
1297 $$ = ParserResult = $1;
1298 CurModule.ModuleDone();
1301 // FunctionList - A list of functions, preceeded by a constant pool.
1303 FunctionList : FunctionList Function {
1305 CurFun.FunctionDone();
1307 | FunctionList FunctionProto {
1310 | FunctionList IMPLEMENTATION {
1314 $$ = CurModule.CurrentModule;
1315 // Resolve circular types before we parse the body of the module
1316 ResolveTypes(CurModule.LateResolveTypes);
1319 // ConstPool - Constants with optional names assigned to them.
1320 ConstPool : ConstPool OptAssign CONST ConstVal {
1321 if (!setValueName($4, $2))
1324 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1325 // Eagerly resolve types. This is not an optimization, this is a
1326 // requirement that is due to the fact that we could have this:
1328 // %list = type { %list * }
1329 // %list = type { %list * } ; repeated type decl
1331 // If types are not resolved eagerly, then the two types will not be
1332 // determined to be the same type!
1334 ResolveTypeTo($2, $4->get());
1336 // TODO: FIXME when Type are not const
1337 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1338 // If this is not a redefinition of a type...
1340 InsertType($4->get(),
1341 inFunctionScope() ? CurFun.Types : CurModule.Types);
1347 | ConstPool FunctionProto { // Function prototypes can be in const pool
1349 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1350 const Type *Ty = $5->getType();
1351 // Global declarations appear in Constant Pool
1352 Constant *Initializer = $5;
1353 if (Initializer == 0)
1354 ThrowException("Global value initializer is not a constant!");
1356 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1357 if (!setValueName(GV, $2)) { // If not redefining...
1358 CurModule.CurrentModule->getGlobalList().push_back(GV);
1359 int Slot = InsertValue(GV, CurModule.Values);
1362 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1364 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1365 (char*)GV->getName().c_str()));
1369 | ConstPool OptAssign EXTERNAL GlobalType Types {
1370 const Type *Ty = *$5;
1371 // Global declarations appear in Constant Pool
1372 GlobalVariable *GV = new GlobalVariable(Ty,$4,GlobalValue::ExternalLinkage);
1373 if (!setValueName(GV, $2)) { // If not redefining...
1374 CurModule.CurrentModule->getGlobalList().push_back(GV);
1375 int Slot = InsertValue(GV, CurModule.Values);
1378 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1380 assert(GV->hasName() && "Not named and not numbered!?");
1381 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1382 (char*)GV->getName().c_str()));
1387 | ConstPool TARGET TargetDefinition {
1389 | /* empty: end of list */ {
1394 BigOrLittle : BIG { $$ = Module::BigEndian; };
1395 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1397 TargetDefinition : ENDIAN '=' BigOrLittle {
1398 CurModule.CurrentModule->setEndianness($3);
1400 | POINTERSIZE '=' EUINT64VAL {
1402 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1404 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1406 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1410 //===----------------------------------------------------------------------===//
1411 // Rules to match Function Headers
1412 //===----------------------------------------------------------------------===//
1414 Name : VAR_ID | STRINGCONSTANT;
1415 OptName : Name | /*empty*/ { $$ = 0; };
1417 ArgVal : Types OptName {
1418 if (*$1 == Type::VoidTy)
1419 ThrowException("void typed arguments are invalid!");
1420 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1423 ArgListH : ArgListH ',' ArgVal {
1429 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1434 ArgList : ArgListH {
1437 | ArgListH ',' DOTDOTDOT {
1439 $$->push_back(std::pair<PATypeHolder*,
1440 char*>(new PATypeHolder(Type::VoidTy), 0));
1443 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1444 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1450 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1452 std::string FunctionName($2);
1454 if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1455 ThrowException("LLVM functions cannot return aggregate types!");
1457 std::vector<const Type*> ParamTypeList;
1458 if ($4) { // If there are arguments...
1459 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1460 I != $4->end(); ++I)
1461 ParamTypeList.push_back(I->first->get());
1464 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1465 if (isVarArg) ParamTypeList.pop_back();
1467 const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1468 const PointerType *PFT = PointerType::get(FT);
1472 // Is the function already in symtab?
1473 if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1474 // Yes it is. If this is the case, either we need to be a forward decl,
1475 // or it needs to be.
1476 if (!CurFun.isDeclare && !Fn->isExternal())
1477 ThrowException("Redefinition of function '" + FunctionName + "'!");
1479 // Make sure to strip off any argument names so we can't get conflicts...
1480 for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1483 } else { // Not already defined?
1484 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1485 CurModule.CurrentModule);
1486 InsertValue(Fn, CurModule.Values);
1487 CurModule.DeclareNewGlobalValue(Fn, ValID::create($2));
1489 free($2); // Free strdup'd memory!
1491 CurFun.FunctionStart(Fn);
1493 // Add all of the arguments we parsed to the function...
1494 if ($4) { // Is null if empty...
1495 if (isVarArg) { // Nuke the last entry
1496 assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1497 "Not a varargs marker!");
1498 delete $4->back().first;
1499 $4->pop_back(); // Delete the last entry
1501 Function::aiterator ArgIt = Fn->abegin();
1502 for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1503 I != $4->end(); ++I, ++ArgIt) {
1504 delete I->first; // Delete the typeholder...
1506 if (setValueName(ArgIt, I->second)) // Insert arg into symtab...
1507 assert(0 && "No arg redef allowed!");
1512 delete $4; // We're now done with the argument list
1516 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1518 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1519 $$ = CurFun.CurrentFunction;
1521 // Make sure that we keep track of the linkage type even if there was a
1522 // previous "declare".
1525 // Resolve circular types before we parse the body of the function.
1526 ResolveTypes(CurFun.LateResolveTypes);
1529 END : ENDTOK | '}'; // Allow end of '}' to end a function
1531 Function : BasicBlockList END {
1535 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1536 $$ = CurFun.CurrentFunction;
1537 CurFun.FunctionDone();
1540 //===----------------------------------------------------------------------===//
1541 // Rules to match Basic Blocks
1542 //===----------------------------------------------------------------------===//
1544 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1545 $$ = ValID::create($1);
1548 $$ = ValID::create($1);
1550 | FPVAL { // Perhaps it's an FP constant?
1551 $$ = ValID::create($1);
1554 $$ = ValID::create(ConstantBool::True);
1557 $$ = ValID::create(ConstantBool::False);
1560 $$ = ValID::createNull();
1563 $$ = ValID::create($1);
1566 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1569 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1570 $$ = ValID::create($1);
1572 | Name { // Is it a named reference...?
1573 $$ = ValID::create($1);
1576 // ValueRef - A reference to a definition... either constant or symbolic
1577 ValueRef : SymbolicValueRef | ConstValueRef;
1580 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1581 // type immediately preceeds the value reference, and allows complex constant
1582 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1583 ResolvedVal : Types ValueRef {
1584 $$ = getVal(*$1, $2); delete $1;
1587 BasicBlockList : BasicBlockList BasicBlock {
1588 ($$ = $1)->getBasicBlockList().push_back($2);
1590 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1591 ($$ = $1)->getBasicBlockList().push_back($2);
1595 // Basic blocks are terminated by branching instructions:
1596 // br, br/cc, switch, ret
1598 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1599 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1602 $1->getInstList().push_back($3);
1606 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1607 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1610 $2->getInstList().push_back($4);
1611 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1617 InstructionList : InstructionList Inst {
1618 $1->getInstList().push_back($2);
1622 $$ = CurBB = new BasicBlock();
1625 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1626 $$ = new ReturnInst($2);
1628 | RET VOID { // Return with no result...
1629 $$ = new ReturnInst();
1631 | BR LABEL ValueRef { // Unconditional Branch...
1632 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1633 } // Conditional Branch...
1634 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1635 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1636 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1637 getVal(Type::BoolTy, $3));
1639 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1640 SwitchInst *S = new SwitchInst(getVal($2, $3),
1641 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1644 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1647 S->addCase(I->first, I->second);
1649 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1650 SwitchInst *S = new SwitchInst(getVal($2, $3),
1651 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1654 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1655 UNWIND ResolvedVal {
1656 const PointerType *PFTy;
1657 const FunctionType *Ty;
1659 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1660 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1661 // Pull out the types of all of the arguments...
1662 std::vector<const Type*> ParamTypes;
1664 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1666 ParamTypes.push_back((*I)->getType());
1669 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1670 if (isVarArg) ParamTypes.pop_back();
1672 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1673 PFTy = PointerType::get(Ty);
1676 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1678 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1679 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1681 if (Normal == 0 || Except == 0)
1682 ThrowException("Invoke instruction without label destinations!");
1684 // Create the call node...
1685 if (!$5) { // Has no arguments?
1686 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1687 } else { // Has arguments?
1688 // Loop through FunctionType's arguments and ensure they are specified
1691 FunctionType::param_iterator I = Ty->param_begin();
1692 FunctionType::param_iterator E = Ty->param_end();
1693 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1695 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1696 if ((*ArgI)->getType() != *I)
1697 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1698 (*I)->getDescription() + "'!");
1700 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1701 ThrowException("Invalid number of parameters detected!");
1703 $$ = new InvokeInst(V, Normal, Except, *$5);
1709 $$ = new UnwindInst();
1714 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1716 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1718 ThrowException("May only switch on a constant pool value!");
1720 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1722 | IntType ConstValueRef ',' LABEL ValueRef {
1723 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1724 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1727 ThrowException("May only switch on a constant pool value!");
1729 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1732 Inst : OptAssign InstVal {
1733 // Is this definition named?? if so, assign the name...
1734 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1739 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1740 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1741 $$->push_back(std::make_pair(getVal(*$1, $3),
1742 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1745 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1747 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1748 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1752 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1753 $$ = new std::vector<Value*>();
1756 | ValueRefList ',' ResolvedVal {
1761 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1762 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1764 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1765 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1766 ThrowException("Arithmetic operator requires integer or FP operands!");
1767 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1769 ThrowException("binary operator returned null!");
1772 | LogicalOps Types ValueRef ',' ValueRef {
1773 if (!(*$2)->isIntegral())
1774 ThrowException("Logical operator requires integral operands!");
1775 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1777 ThrowException("binary operator returned null!");
1780 | SetCondOps Types ValueRef ',' ValueRef {
1781 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1783 ThrowException("binary operator returned null!");
1787 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1788 << " Replacing with 'xor'.\n";
1790 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1792 ThrowException("Expected integral type for not instruction!");
1794 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1796 ThrowException("Could not create a xor instruction!");
1798 | ShiftOps ResolvedVal ',' ResolvedVal {
1799 if ($4->getType() != Type::UByteTy)
1800 ThrowException("Shift amount must be ubyte!");
1801 if (!$2->getType()->isInteger())
1802 ThrowException("Shift constant expression requires integer operand!");
1803 $$ = new ShiftInst($1, $2, $4);
1805 | CAST ResolvedVal TO Types {
1806 if (!$4->get()->isFirstClassType())
1807 ThrowException("cast instruction to a non-primitive type: '" +
1808 $4->get()->getDescription() + "'!");
1809 $$ = new CastInst($2, *$4);
1812 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1813 if ($2->getType() != Type::BoolTy)
1814 ThrowException("select condition must be boolean!");
1815 if ($4->getType() != $6->getType())
1816 ThrowException("select value types should match!");
1817 $$ = new SelectInst($2, $4, $6);
1819 | VA_ARG ResolvedVal ',' Types {
1820 // FIXME: This is emulation code for an obsolete syntax. This should be
1821 // removed at some point.
1822 if (!ObsoleteVarArgs) {
1823 std::cerr << "WARNING: this file uses obsolete features. "
1824 << "Assemble and disassemble to update it.\n";
1825 ObsoleteVarArgs = true;
1828 // First, load the valist...
1829 Instruction *CurVAList = new LoadInst($2, "");
1830 CurBB->getInstList().push_back(CurVAList);
1832 // Emit the vaarg instruction.
1833 $$ = new VAArgInst(CurVAList, *$4);
1835 // Now we must advance the pointer and update it in memory.
1836 Instruction *TheVANext = new VANextInst(CurVAList, *$4);
1837 CurBB->getInstList().push_back(TheVANext);
1839 CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
1842 | VAARG ResolvedVal ',' Types {
1843 $$ = new VAArgInst($2, *$4);
1846 | VANEXT ResolvedVal ',' Types {
1847 $$ = new VANextInst($2, *$4);
1851 const Type *Ty = $2->front().first->getType();
1852 if (!Ty->isFirstClassType())
1853 ThrowException("PHI node operands must be of first class type!");
1854 $$ = new PHINode(Ty);
1855 $$->op_reserve($2->size()*2);
1856 while ($2->begin() != $2->end()) {
1857 if ($2->front().first->getType() != Ty)
1858 ThrowException("All elements of a PHI node must be of the same type!");
1859 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1862 delete $2; // Free the list...
1864 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1865 const PointerType *PFTy;
1866 const FunctionType *Ty;
1868 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1869 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1870 // Pull out the types of all of the arguments...
1871 std::vector<const Type*> ParamTypes;
1873 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1875 ParamTypes.push_back((*I)->getType());
1878 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1879 if (isVarArg) ParamTypes.pop_back();
1881 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1882 PFTy = PointerType::get(Ty);
1885 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1887 // Create the call node...
1888 if (!$5) { // Has no arguments?
1889 // Make sure no arguments is a good thing!
1890 if (Ty->getNumParams() != 0)
1891 ThrowException("No arguments passed to a function that "
1892 "expects arguments!");
1894 $$ = new CallInst(V, std::vector<Value*>());
1895 } else { // Has arguments?
1896 // Loop through FunctionType's arguments and ensure they are specified
1899 FunctionType::param_iterator I = Ty->param_begin();
1900 FunctionType::param_iterator E = Ty->param_end();
1901 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1903 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1904 if ((*ArgI)->getType() != *I)
1905 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1906 (*I)->getDescription() + "'!");
1908 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1909 ThrowException("Invalid number of parameters detected!");
1911 $$ = new CallInst(V, *$5);
1921 // IndexList - List of indices for GEP based instructions...
1922 IndexList : ',' ValueRefList {
1925 $$ = new std::vector<Value*>();
1928 OptVolatile : VOLATILE {
1936 MemoryInst : MALLOC Types {
1937 $$ = new MallocInst(*$2);
1940 | MALLOC Types ',' UINT ValueRef {
1941 $$ = new MallocInst(*$2, getVal($4, $5));
1945 $$ = new AllocaInst(*$2);
1948 | ALLOCA Types ',' UINT ValueRef {
1949 $$ = new AllocaInst(*$2, getVal($4, $5));
1952 | FREE ResolvedVal {
1953 if (!isa<PointerType>($2->getType()))
1954 ThrowException("Trying to free nonpointer type " +
1955 $2->getType()->getDescription() + "!");
1956 $$ = new FreeInst($2);
1959 | OptVolatile LOAD Types ValueRef {
1960 if (!isa<PointerType>($3->get()))
1961 ThrowException("Can't load from nonpointer type: " +
1962 (*$3)->getDescription());
1963 $$ = new LoadInst(getVal(*$3, $4), "", $1);
1966 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
1967 const PointerType *PT = dyn_cast<PointerType>($5->get());
1969 ThrowException("Can't store to a nonpointer type: " +
1970 (*$5)->getDescription());
1971 const Type *ElTy = PT->getElementType();
1972 if (ElTy != $3->getType())
1973 ThrowException("Can't store '" + $3->getType()->getDescription() +
1974 "' into space of type '" + ElTy->getDescription() + "'!");
1976 $$ = new StoreInst($3, getVal(*$5, $6), $1);
1979 | GETELEMENTPTR Types ValueRef IndexList {
1980 if (!isa<PointerType>($2->get()))
1981 ThrowException("getelementptr insn requires pointer operand!");
1982 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1983 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1984 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1985 delete $2; delete $4;
1990 int yyerror(const char *ErrorMsg) {
1992 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
1993 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
1994 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
1995 if (yychar == YYEMPTY || yychar == 0)
1996 errMsg += "end-of-file.";
1998 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
1999 ThrowException(errMsg);