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/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/SymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/Streams.h"
29 // The following is a gross hack. In order to rid the libAsmParser library of
30 // exceptions, we have to have a way of getting the yyparse function to go into
31 // an error situation. So, whenever we want an error to occur, the GenerateError
32 // function (see bottom of file) sets TriggerError. Then, at the end of each
33 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
34 // (a goto) to put YACC in error state. Furthermore, several calls to
35 // GenerateError are made from inside productions and they must simulate the
36 // previous exception behavior by exiting the production immediately. We have
37 // replaced these with the GEN_ERROR macro which calls GeneratError and then
38 // immediately invokes YYERROR. This would be so much cleaner if it was a
39 // recursive descent parser.
40 static bool TriggerError = false;
41 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
42 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
44 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
45 int yylex(); // declaration" of xxx warnings.
49 std::string CurFilename;
53 static Module *ParserResult;
55 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
56 // relating to upreferences in the input stream.
58 //#define DEBUG_UPREFS 1
60 #define UR_OUT(X) llvm_cerr << X
65 #define YYERROR_VERBOSE 1
67 static bool ObsoleteVarArgs;
68 static bool NewVarArgs;
69 static BasicBlock *CurBB;
70 static GlobalVariable *CurGV;
73 // This contains info used when building the body of a function. It is
74 // destroyed when the function is completed.
76 typedef std::vector<Value *> ValueList; // Numbered defs
78 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
79 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
81 static struct PerModuleInfo {
82 Module *CurrentModule;
83 std::map<const Type *, ValueList> Values; // Module level numbered definitions
84 std::map<const Type *,ValueList> LateResolveValues;
85 std::vector<PATypeHolder> Types;
86 std::map<ValID, PATypeHolder> LateResolveTypes;
88 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
89 /// how they were referenced and on which line of the input they came from so
90 /// that we can resolve them later and print error messages as appropriate.
91 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
93 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
94 // references to global values. Global values may be referenced before they
95 // are defined, and if so, the temporary object that they represent is held
96 // here. This is used for forward references of GlobalValues.
98 typedef std::map<std::pair<const PointerType *,
99 ValID>, GlobalValue*> GlobalRefsType;
100 GlobalRefsType GlobalRefs;
103 // If we could not resolve some functions at function compilation time
104 // (calls to functions before they are defined), resolve them now... Types
105 // are resolved when the constant pool has been completely parsed.
107 ResolveDefinitions(LateResolveValues);
111 // Check to make sure that all global value forward references have been
114 if (!GlobalRefs.empty()) {
115 std::string UndefinedReferences = "Unresolved global references exist:\n";
117 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
119 UndefinedReferences += " " + I->first.first->getDescription() + " " +
120 I->first.second.getName() + "\n";
122 GenerateError(UndefinedReferences);
126 Values.clear(); // Clear out function local definitions
131 // GetForwardRefForGlobal - Check to see if there is a forward reference
132 // for this global. If so, remove it from the GlobalRefs map and return it.
133 // If not, just return null.
134 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
135 // Check to see if there is a forward reference to this global variable...
136 // if there is, eliminate it and patch the reference to use the new def'n.
137 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
138 GlobalValue *Ret = 0;
139 if (I != GlobalRefs.end()) {
147 static struct PerFunctionInfo {
148 Function *CurrentFunction; // Pointer to current function being created
150 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
151 std::map<const Type*, ValueList> LateResolveValues;
152 bool isDeclare; // Is this function a forward declararation?
153 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
155 /// BBForwardRefs - When we see forward references to basic blocks, keep
156 /// track of them here.
157 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
158 std::vector<BasicBlock*> NumberedBlocks;
161 inline PerFunctionInfo() {
164 Linkage = GlobalValue::ExternalLinkage;
167 inline void FunctionStart(Function *M) {
172 void FunctionDone() {
173 NumberedBlocks.clear();
175 // Any forward referenced blocks left?
176 if (!BBForwardRefs.empty()) {
177 GenerateError("Undefined reference to label " +
178 BBForwardRefs.begin()->first->getName());
182 // Resolve all forward references now.
183 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
185 Values.clear(); // Clear out function local definitions
188 Linkage = GlobalValue::ExternalLinkage;
190 } CurFun; // Info for the current function...
192 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
195 //===----------------------------------------------------------------------===//
196 // Code to handle definitions of all the types
197 //===----------------------------------------------------------------------===//
199 static int InsertValue(Value *V,
200 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
201 if (V->hasName()) return -1; // Is this a numbered definition?
203 // Yes, insert the value into the value table...
204 ValueList &List = ValueTab[V->getType()];
206 return List.size()-1;
209 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
211 case ValID::NumberVal: // Is it a numbered definition?
212 // Module constants occupy the lowest numbered slots...
213 if ((unsigned)D.Num < CurModule.Types.size())
214 return CurModule.Types[(unsigned)D.Num];
216 case ValID::NameVal: // Is it a named definition?
217 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
218 D.destroy(); // Free old strdup'd memory...
223 GenerateError("Internal parser error: Invalid symbol type reference!");
227 // If we reached here, we referenced either a symbol that we don't know about
228 // or an id number that hasn't been read yet. We may be referencing something
229 // forward, so just create an entry to be resolved later and get to it...
231 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
234 if (inFunctionScope()) {
235 if (D.Type == ValID::NameVal) {
236 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
239 GenerateError("Reference to an undefined type: #" + itostr(D.Num));
244 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
245 if (I != CurModule.LateResolveTypes.end())
248 Type *Typ = OpaqueType::get();
249 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
253 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
254 SymbolTable &SymTab =
255 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
256 CurModule.CurrentModule->getSymbolTable();
257 return SymTab.lookup(Ty, Name);
260 // getValNonImprovising - Look up the value specified by the provided type and
261 // the provided ValID. If the value exists and has already been defined, return
262 // it. Otherwise return null.
264 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
265 if (isa<FunctionType>(Ty)) {
266 GenerateError("Functions are not values and "
267 "must be referenced as pointers");
272 case ValID::NumberVal: { // Is it a numbered definition?
273 unsigned Num = (unsigned)D.Num;
275 // Module constants occupy the lowest numbered slots...
276 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
277 if (VI != CurModule.Values.end()) {
278 if (Num < VI->second.size())
279 return VI->second[Num];
280 Num -= VI->second.size();
283 // Make sure that our type is within bounds
284 VI = CurFun.Values.find(Ty);
285 if (VI == CurFun.Values.end()) return 0;
287 // Check that the number is within bounds...
288 if (VI->second.size() <= Num) return 0;
290 return VI->second[Num];
293 case ValID::NameVal: { // Is it a named definition?
294 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
295 if (N == 0) return 0;
297 D.destroy(); // Free old strdup'd memory...
301 // Check to make sure that "Ty" is an integral type, and that our
302 // value will fit into the specified type...
303 case ValID::ConstSIntVal: // Is it a constant pool reference??
304 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
305 GenerateError("Signed integral constant '" +
306 itostr(D.ConstPool64) + "' is invalid for type '" +
307 Ty->getDescription() + "'!");
310 return ConstantInt::get(Ty, D.ConstPool64);
312 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
313 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
314 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
315 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
316 "' is invalid or out of range!");
318 } else { // This is really a signed reference. Transmogrify.
319 return ConstantInt::get(Ty, D.ConstPool64);
322 return ConstantInt::get(Ty, D.UConstPool64);
325 case ValID::ConstFPVal: // Is it a floating point const pool reference?
326 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
327 GenerateError("FP constant invalid for type!!");
330 return ConstantFP::get(Ty, D.ConstPoolFP);
332 case ValID::ConstNullVal: // Is it a null value?
333 if (!isa<PointerType>(Ty)) {
334 GenerateError("Cannot create a a non pointer null!");
337 return ConstantPointerNull::get(cast<PointerType>(Ty));
339 case ValID::ConstUndefVal: // Is it an undef value?
340 return UndefValue::get(Ty);
342 case ValID::ConstZeroVal: // Is it a zero value?
343 return Constant::getNullValue(Ty);
345 case ValID::ConstantVal: // Fully resolved constant?
346 if (D.ConstantValue->getType() != Ty) {
347 GenerateError("Constant expression type different from required type!");
350 return D.ConstantValue;
352 case ValID::InlineAsmVal: { // Inline asm expression
353 const PointerType *PTy = dyn_cast<PointerType>(Ty);
354 const FunctionType *FTy =
355 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
356 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
357 GenerateError("Invalid type for asm constraint string!");
360 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
361 D.IAD->HasSideEffects);
362 D.destroy(); // Free InlineAsmDescriptor.
366 assert(0 && "Unhandled case!");
370 assert(0 && "Unhandled case!");
374 // getVal - This function is identical to getValNonImprovising, except that if a
375 // value is not already defined, it "improvises" by creating a placeholder var
376 // that looks and acts just like the requested variable. When the value is
377 // defined later, all uses of the placeholder variable are replaced with the
380 static Value *getVal(const Type *Ty, const ValID &ID) {
381 if (Ty == Type::LabelTy) {
382 GenerateError("Cannot use a basic block here");
386 // See if the value has already been defined.
387 Value *V = getValNonImprovising(Ty, ID);
389 if (TriggerError) return 0;
391 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
392 GenerateError("Invalid use of a composite type!");
396 // If we reached here, we referenced either a symbol that we don't know about
397 // or an id number that hasn't been read yet. We may be referencing something
398 // forward, so just create an entry to be resolved later and get to it...
400 V = new Argument(Ty);
402 // Remember where this forward reference came from. FIXME, shouldn't we try
403 // to recycle these things??
404 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
407 if (inFunctionScope())
408 InsertValue(V, CurFun.LateResolveValues);
410 InsertValue(V, CurModule.LateResolveValues);
414 /// getBBVal - This is used for two purposes:
415 /// * If isDefinition is true, a new basic block with the specified ID is being
417 /// * If isDefinition is true, this is a reference to a basic block, which may
418 /// or may not be a forward reference.
420 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
421 assert(inFunctionScope() && "Can't get basic block at global scope!");
427 GenerateError("Illegal label reference " + ID.getName());
429 case ValID::NumberVal: // Is it a numbered definition?
430 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
431 CurFun.NumberedBlocks.resize(ID.Num+1);
432 BB = CurFun.NumberedBlocks[ID.Num];
434 case ValID::NameVal: // Is it a named definition?
436 if (Value *N = CurFun.CurrentFunction->
437 getSymbolTable().lookup(Type::LabelTy, Name))
438 BB = cast<BasicBlock>(N);
442 // See if the block has already been defined.
444 // If this is the definition of the block, make sure the existing value was
445 // just a forward reference. If it was a forward reference, there will be
446 // an entry for it in the PlaceHolderInfo map.
447 if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
448 // The existing value was a definition, not a forward reference.
449 GenerateError("Redefinition of label " + ID.getName());
453 ID.destroy(); // Free strdup'd memory.
457 // Otherwise this block has not been seen before.
458 BB = new BasicBlock("", CurFun.CurrentFunction);
459 if (ID.Type == ValID::NameVal) {
460 BB->setName(ID.Name);
462 CurFun.NumberedBlocks[ID.Num] = BB;
465 // If this is not a definition, keep track of it so we can use it as a forward
468 // Remember where this forward reference came from.
469 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
471 // The forward declaration could have been inserted anywhere in the
472 // function: insert it into the correct place now.
473 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
474 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
481 //===----------------------------------------------------------------------===//
482 // Code to handle forward references in instructions
483 //===----------------------------------------------------------------------===//
485 // This code handles the late binding needed with statements that reference
486 // values not defined yet... for example, a forward branch, or the PHI node for
489 // This keeps a table (CurFun.LateResolveValues) of all such forward references
490 // and back patchs after we are done.
493 // ResolveDefinitions - If we could not resolve some defs at parsing
494 // time (forward branches, phi functions for loops, etc...) resolve the
498 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
499 std::map<const Type*,ValueList> *FutureLateResolvers) {
500 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
501 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
502 E = LateResolvers.end(); LRI != E; ++LRI) {
503 ValueList &List = LRI->second;
504 while (!List.empty()) {
505 Value *V = List.back();
508 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
509 CurModule.PlaceHolderInfo.find(V);
510 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
512 ValID &DID = PHI->second.first;
514 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
518 V->replaceAllUsesWith(TheRealValue);
520 CurModule.PlaceHolderInfo.erase(PHI);
521 } else if (FutureLateResolvers) {
522 // Functions have their unresolved items forwarded to the module late
524 InsertValue(V, *FutureLateResolvers);
526 if (DID.Type == ValID::NameVal) {
527 GenerateError("Reference to an invalid definition: '" +DID.getName()+
528 "' of type '" + V->getType()->getDescription() + "'",
532 GenerateError("Reference to an invalid definition: #" +
533 itostr(DID.Num) + " of type '" +
534 V->getType()->getDescription() + "'",
542 LateResolvers.clear();
545 // ResolveTypeTo - A brand new type was just declared. This means that (if
546 // name is not null) things referencing Name can be resolved. Otherwise, things
547 // refering to the number can be resolved. Do this now.
549 static void ResolveTypeTo(char *Name, const Type *ToTy) {
551 if (Name) D = ValID::create(Name);
552 else D = ValID::create((int)CurModule.Types.size());
554 std::map<ValID, PATypeHolder>::iterator I =
555 CurModule.LateResolveTypes.find(D);
556 if (I != CurModule.LateResolveTypes.end()) {
557 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
558 CurModule.LateResolveTypes.erase(I);
562 // setValueName - Set the specified value to the name given. The name may be
563 // null potentially, in which case this is a noop. The string passed in is
564 // assumed to be a malloc'd string buffer, and is free'd by this function.
566 static void setValueName(Value *V, char *NameStr) {
568 std::string Name(NameStr); // Copy string
569 free(NameStr); // Free old string
571 if (V->getType() == Type::VoidTy) {
572 GenerateError("Can't assign name '" + Name+"' to value with void type!");
576 assert(inFunctionScope() && "Must be in function scope!");
577 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
578 if (ST.lookup(V->getType(), Name)) {
579 GenerateError("Redefinition of value named '" + Name + "' in the '" +
580 V->getType()->getDescription() + "' type plane!");
589 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
590 /// this is a declaration, otherwise it is a definition.
591 static GlobalVariable *
592 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
593 bool isConstantGlobal, const Type *Ty,
594 Constant *Initializer) {
595 if (isa<FunctionType>(Ty)) {
596 GenerateError("Cannot declare global vars of function type!");
600 const PointerType *PTy = PointerType::get(Ty);
604 Name = NameStr; // Copy string
605 free(NameStr); // Free old string
608 // See if this global value was forward referenced. If so, recycle the
612 ID = ValID::create((char*)Name.c_str());
614 ID = ValID::create((int)CurModule.Values[PTy].size());
617 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
618 // Move the global to the end of the list, from whereever it was
619 // previously inserted.
620 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
621 CurModule.CurrentModule->getGlobalList().remove(GV);
622 CurModule.CurrentModule->getGlobalList().push_back(GV);
623 GV->setInitializer(Initializer);
624 GV->setLinkage(Linkage);
625 GV->setConstant(isConstantGlobal);
626 InsertValue(GV, CurModule.Values);
630 // If this global has a name, check to see if there is already a definition
631 // of this global in the module. If so, merge as appropriate. Note that
632 // this is really just a hack around problems in the CFE. :(
634 // We are a simple redefinition of a value, check to see if it is defined
635 // the same as the old one.
636 if (GlobalVariable *EGV =
637 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
638 // We are allowed to redefine a global variable in two circumstances:
639 // 1. If at least one of the globals is uninitialized or
640 // 2. If both initializers have the same value.
642 if (!EGV->hasInitializer() || !Initializer ||
643 EGV->getInitializer() == Initializer) {
645 // Make sure the existing global version gets the initializer! Make
646 // sure that it also gets marked const if the new version is.
647 if (Initializer && !EGV->hasInitializer())
648 EGV->setInitializer(Initializer);
649 if (isConstantGlobal)
650 EGV->setConstant(true);
651 EGV->setLinkage(Linkage);
655 GenerateError("Redefinition of global variable named '" + Name +
656 "' in the '" + Ty->getDescription() + "' type plane!");
661 // Otherwise there is no existing GV to use, create one now.
663 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
664 CurModule.CurrentModule);
665 InsertValue(GV, CurModule.Values);
669 // setTypeName - Set the specified type to the name given. The name may be
670 // null potentially, in which case this is a noop. The string passed in is
671 // assumed to be a malloc'd string buffer, and is freed by this function.
673 // This function returns true if the type has already been defined, but is
674 // allowed to be redefined in the specified context. If the name is a new name
675 // for the type plane, it is inserted and false is returned.
676 static bool setTypeName(const Type *T, char *NameStr) {
677 assert(!inFunctionScope() && "Can't give types function-local names!");
678 if (NameStr == 0) return false;
680 std::string Name(NameStr); // Copy string
681 free(NameStr); // Free old string
683 // We don't allow assigning names to void type
684 if (T == Type::VoidTy) {
685 GenerateError("Can't assign name '" + Name + "' to the void type!");
689 // Set the type name, checking for conflicts as we do so.
690 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
692 if (AlreadyExists) { // Inserting a name that is already defined???
693 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
694 assert(Existing && "Conflict but no matching type?");
696 // There is only one case where this is allowed: when we are refining an
697 // opaque type. In this case, Existing will be an opaque type.
698 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
699 // We ARE replacing an opaque type!
700 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
704 // Otherwise, this is an attempt to redefine a type. That's okay if
705 // the redefinition is identical to the original. This will be so if
706 // Existing and T point to the same Type object. In this one case we
707 // allow the equivalent redefinition.
708 if (Existing == T) return true; // Yes, it's equal.
710 // Any other kind of (non-equivalent) redefinition is an error.
711 GenerateError("Redefinition of type named '" + Name + "' in the '" +
712 T->getDescription() + "' type plane!");
718 //===----------------------------------------------------------------------===//
719 // Code for handling upreferences in type names...
722 // TypeContains - Returns true if Ty directly contains E in it.
724 static bool TypeContains(const Type *Ty, const Type *E) {
725 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
726 E) != Ty->subtype_end();
731 // NestingLevel - The number of nesting levels that need to be popped before
732 // this type is resolved.
733 unsigned NestingLevel;
735 // LastContainedTy - This is the type at the current binding level for the
736 // type. Every time we reduce the nesting level, this gets updated.
737 const Type *LastContainedTy;
739 // UpRefTy - This is the actual opaque type that the upreference is
743 UpRefRecord(unsigned NL, OpaqueType *URTy)
744 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
748 // UpRefs - A list of the outstanding upreferences that need to be resolved.
749 static std::vector<UpRefRecord> UpRefs;
751 /// HandleUpRefs - Every time we finish a new layer of types, this function is
752 /// called. It loops through the UpRefs vector, which is a list of the
753 /// currently active types. For each type, if the up reference is contained in
754 /// the newly completed type, we decrement the level count. When the level
755 /// count reaches zero, the upreferenced type is the type that is passed in:
756 /// thus we can complete the cycle.
758 static PATypeHolder HandleUpRefs(const Type *ty) {
759 // If Ty isn't abstract, or if there are no up-references in it, then there is
760 // nothing to resolve here.
761 if (!ty->isAbstract() || UpRefs.empty()) return ty;
764 UR_OUT("Type '" << Ty->getDescription() <<
765 "' newly formed. Resolving upreferences.\n" <<
766 UpRefs.size() << " upreferences active!\n");
768 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
769 // to zero), we resolve them all together before we resolve them to Ty. At
770 // the end of the loop, if there is anything to resolve to Ty, it will be in
772 OpaqueType *TypeToResolve = 0;
774 for (unsigned i = 0; i != UpRefs.size(); ++i) {
775 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
776 << UpRefs[i].second->getDescription() << ") = "
777 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
778 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
779 // Decrement level of upreference
780 unsigned Level = --UpRefs[i].NestingLevel;
781 UpRefs[i].LastContainedTy = Ty;
782 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
783 if (Level == 0) { // Upreference should be resolved!
784 if (!TypeToResolve) {
785 TypeToResolve = UpRefs[i].UpRefTy;
787 UR_OUT(" * Resolving upreference for "
788 << UpRefs[i].second->getDescription() << "\n";
789 std::string OldName = UpRefs[i].UpRefTy->getDescription());
790 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
791 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
792 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
794 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
795 --i; // Do not skip the next element...
801 UR_OUT(" * Resolving upreference for "
802 << UpRefs[i].second->getDescription() << "\n";
803 std::string OldName = TypeToResolve->getDescription());
804 TypeToResolve->refineAbstractTypeTo(Ty);
810 // common code from the two 'RunVMAsmParser' functions
811 static Module* RunParser(Module * M) {
813 llvmAsmlineno = 1; // Reset the current line number...
814 ObsoleteVarArgs = false;
816 CurModule.CurrentModule = M;
818 // Check to make sure the parser succeeded
825 // Check to make sure that parsing produced a result
829 // Reset ParserResult variable while saving its value for the result.
830 Module *Result = ParserResult;
833 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
836 if ((F = Result->getNamedFunction("llvm.va_start"))
837 && F->getFunctionType()->getNumParams() == 0)
838 ObsoleteVarArgs = true;
839 if((F = Result->getNamedFunction("llvm.va_copy"))
840 && F->getFunctionType()->getNumParams() == 1)
841 ObsoleteVarArgs = true;
844 if (ObsoleteVarArgs && NewVarArgs) {
846 "This file is corrupt: it uses both new and old style varargs");
850 if(ObsoleteVarArgs) {
851 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
852 if (F->arg_size() != 0) {
853 GenerateError("Obsolete va_start takes 0 argument!");
859 //bar = alloca typeof(foo)
863 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
864 const Type* ArgTy = F->getFunctionType()->getReturnType();
865 const Type* ArgTyPtr = PointerType::get(ArgTy);
866 Function* NF = Result->getOrInsertFunction("llvm.va_start",
867 RetTy, ArgTyPtr, (Type *)0);
869 while (!F->use_empty()) {
870 CallInst* CI = cast<CallInst>(F->use_back());
871 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
872 new CallInst(NF, bar, "", CI);
873 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
874 CI->replaceAllUsesWith(foo);
875 CI->getParent()->getInstList().erase(CI);
877 Result->getFunctionList().erase(F);
880 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
881 if(F->arg_size() != 1) {
882 GenerateError("Obsolete va_end takes 1 argument!");
888 //bar = alloca 1 of typeof(foo)
890 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
891 const Type* ArgTy = F->getFunctionType()->getParamType(0);
892 const Type* ArgTyPtr = PointerType::get(ArgTy);
893 Function* NF = Result->getOrInsertFunction("llvm.va_end",
894 RetTy, ArgTyPtr, (Type *)0);
896 while (!F->use_empty()) {
897 CallInst* CI = cast<CallInst>(F->use_back());
898 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
899 new StoreInst(CI->getOperand(1), bar, CI);
900 new CallInst(NF, bar, "", CI);
901 CI->getParent()->getInstList().erase(CI);
903 Result->getFunctionList().erase(F);
906 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
907 if(F->arg_size() != 1) {
908 GenerateError("Obsolete va_copy takes 1 argument!");
913 //a = alloca 1 of typeof(foo)
914 //b = alloca 1 of typeof(foo)
919 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
920 const Type* ArgTy = F->getFunctionType()->getReturnType();
921 const Type* ArgTyPtr = PointerType::get(ArgTy);
922 Function* NF = Result->getOrInsertFunction("llvm.va_copy",
923 RetTy, ArgTyPtr, ArgTyPtr,
926 while (!F->use_empty()) {
927 CallInst* CI = cast<CallInst>(F->use_back());
928 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
929 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
930 new StoreInst(CI->getOperand(1), b, CI);
931 new CallInst(NF, a, b, "", CI);
932 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
933 CI->replaceAllUsesWith(foo);
934 CI->getParent()->getInstList().erase(CI);
936 Result->getFunctionList().erase(F);
943 //===----------------------------------------------------------------------===//
944 // RunVMAsmParser - Define an interface to this parser
945 //===----------------------------------------------------------------------===//
947 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
950 CurFilename = Filename;
951 return RunParser(new Module(CurFilename));
954 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
955 set_scan_string(AsmString);
957 CurFilename = "from_memory";
959 return RunParser(new Module (CurFilename));
968 llvm::Module *ModuleVal;
969 llvm::Function *FunctionVal;
970 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
971 llvm::BasicBlock *BasicBlockVal;
972 llvm::TerminatorInst *TermInstVal;
973 llvm::Instruction *InstVal;
974 llvm::Constant *ConstVal;
976 const llvm::Type *PrimType;
977 llvm::PATypeHolder *TypeVal;
978 llvm::Value *ValueVal;
980 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
981 std::vector<llvm::Value*> *ValueList;
982 std::list<llvm::PATypeHolder> *TypeList;
983 // Represent the RHS of PHI node
984 std::list<std::pair<llvm::Value*,
985 llvm::BasicBlock*> > *PHIList;
986 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
987 std::vector<llvm::Constant*> *ConstVector;
989 llvm::GlobalValue::LinkageTypes Linkage;
997 char *StrVal; // This memory is strdup'd!
998 llvm::ValID ValIDVal; // strdup'd memory maybe!
1000 llvm::Instruction::BinaryOps BinaryOpVal;
1001 llvm::Instruction::TermOps TermOpVal;
1002 llvm::Instruction::MemoryOps MemOpVal;
1003 llvm::Instruction::CastOps CastOpVal;
1004 llvm::Instruction::OtherOps OtherOpVal;
1005 llvm::Module::Endianness Endianness;
1006 llvm::ICmpInst::Predicate IPredicate;
1007 llvm::FCmpInst::Predicate FPredicate;
1010 %type <ModuleVal> Module FunctionList
1011 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1012 %type <BasicBlockVal> BasicBlock InstructionList
1013 %type <TermInstVal> BBTerminatorInst
1014 %type <InstVal> Inst InstVal MemoryInst
1015 %type <ConstVal> ConstVal ConstExpr
1016 %type <ConstVector> ConstVector
1017 %type <ArgList> ArgList ArgListH
1018 %type <ArgVal> ArgVal
1019 %type <PHIList> PHIList
1020 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1021 %type <ValueList> IndexList // For GEP derived indices
1022 %type <TypeList> TypeListI ArgTypeListI
1023 %type <JumpTable> JumpTable
1024 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1025 %type <BoolVal> OptVolatile // 'volatile' or not
1026 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1027 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1028 %type <Linkage> OptLinkage
1029 %type <Endianness> BigOrLittle
1031 // ValueRef - Unresolved reference to a definition or BB
1032 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1033 %type <ValueVal> ResolvedVal // <type> <valref> pair
1034 // Tokens and types for handling constant integer values
1036 // ESINT64VAL - A negative number within long long range
1037 %token <SInt64Val> ESINT64VAL
1039 // EUINT64VAL - A positive number within uns. long long range
1040 %token <UInt64Val> EUINT64VAL
1041 %type <SInt64Val> EINT64VAL
1043 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1044 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1045 %type <SIntVal> INTVAL
1046 %token <FPVal> FPVAL // Float or Double constant
1048 // Built in types...
1049 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1050 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1051 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1052 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1054 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1055 %type <StrVal> Name OptName OptAssign
1056 %type <UIntVal> OptAlign OptCAlign
1057 %type <StrVal> OptSection SectionString
1059 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1060 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1061 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1062 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1063 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1064 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1065 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1066 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1068 %type <UIntVal> OptCallingConv
1070 // Basic Block Terminating Operators
1071 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1074 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1075 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1076 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1077 %token <OtherOpVal> ICMP FCMP
1078 %type <IPredicate> IPredicates
1079 %type <FPredicate> FPredicates
1080 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1081 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1083 // Memory Instructions
1084 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1087 %type <CastOpVal> CastOps
1088 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1089 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1092 %type <OtherOpVal> ShiftOps
1093 %token <OtherOpVal> PHI_TOK SELECT SHL LSHR ASHR VAARG
1094 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1095 %token VAARG_old VANEXT_old //OBSOLETE
1101 // Handle constant integer size restriction and conversion...
1105 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1106 GEN_ERROR("Value too large for type!");
1112 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
1113 EINT64VAL : EUINT64VAL {
1114 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1115 GEN_ERROR("Value too large for type!");
1120 // Operations that are notably excluded from this list include:
1121 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1123 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1124 LogicalOps : AND | OR | XOR;
1125 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1126 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1127 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1128 ShiftOps : SHL | LSHR | ASHR;
1130 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1131 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1132 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1133 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1134 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1138 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1139 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1140 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1141 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1142 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1143 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1144 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1145 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1146 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1149 // These are some types that allow classification if we only want a particular
1150 // thing... for example, only a signed, unsigned, or integral type.
1151 SIntType : LONG | INT | SHORT | SBYTE;
1152 UIntType : ULONG | UINT | USHORT | UBYTE;
1153 IntType : SIntType | UIntType;
1154 FPType : FLOAT | DOUBLE;
1156 // OptAssign - Value producing statements have an optional assignment component
1157 OptAssign : Name '=' {
1166 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1167 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1168 WEAK { $$ = GlobalValue::WeakLinkage; } |
1169 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1170 DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; } |
1171 DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; } |
1172 EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; } |
1173 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1175 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1176 CCC_TOK { $$ = CallingConv::C; } |
1177 CSRETCC_TOK { $$ = CallingConv::CSRet; } |
1178 FASTCC_TOK { $$ = CallingConv::Fast; } |
1179 COLDCC_TOK { $$ = CallingConv::Cold; } |
1180 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1181 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1183 if ((unsigned)$2 != $2)
1184 GEN_ERROR("Calling conv too large!");
1189 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1190 // a comma before it.
1191 OptAlign : /*empty*/ { $$ = 0; } |
1194 if ($$ != 0 && !isPowerOf2_32($$))
1195 GEN_ERROR("Alignment must be a power of two!");
1198 OptCAlign : /*empty*/ { $$ = 0; } |
1199 ',' ALIGN EUINT64VAL {
1201 if ($$ != 0 && !isPowerOf2_32($$))
1202 GEN_ERROR("Alignment must be a power of two!");
1207 SectionString : SECTION STRINGCONSTANT {
1208 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1209 if ($2[i] == '"' || $2[i] == '\\')
1210 GEN_ERROR("Invalid character in section name!");
1215 OptSection : /*empty*/ { $$ = 0; } |
1216 SectionString { $$ = $1; };
1218 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1219 // is set to be the global we are processing.
1221 GlobalVarAttributes : /* empty */ {} |
1222 ',' GlobalVarAttribute GlobalVarAttributes {};
1223 GlobalVarAttribute : SectionString {
1224 CurGV->setSection($1);
1228 | ALIGN EUINT64VAL {
1229 if ($2 != 0 && !isPowerOf2_32($2))
1230 GEN_ERROR("Alignment must be a power of two!");
1231 CurGV->setAlignment($2);
1235 //===----------------------------------------------------------------------===//
1236 // Types includes all predefined types... except void, because it can only be
1237 // used in specific contexts (function returning void for example). To have
1238 // access to it, a user must explicitly use TypesV.
1241 // TypesV includes all of 'Types', but it also includes the void type.
1242 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1243 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1246 if (!UpRefs.empty())
1247 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1253 // Derived types are added later...
1255 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1256 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1258 $$ = new PATypeHolder(OpaqueType::get());
1262 $$ = new PATypeHolder($1);
1265 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1266 const Type* tmp = getTypeVal($1);
1268 $$ = new PATypeHolder(tmp);
1271 // Include derived types in the Types production.
1273 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1274 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1275 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1276 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1277 $$ = new PATypeHolder(OT);
1278 UR_OUT("New Upreference!\n");
1281 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1282 std::vector<const Type*> Params;
1283 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1284 E = $3->end(); I != E; ++I)
1285 Params.push_back(*I);
1286 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1287 if (isVarArg) Params.pop_back();
1289 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1290 delete $3; // Delete the argument list
1291 delete $1; // Delete the return type handle
1294 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1295 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1299 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1300 const llvm::Type* ElemTy = $4->get();
1301 if ((unsigned)$2 != $2)
1302 GEN_ERROR("Unsigned result not equal to signed result");
1303 if (!ElemTy->isPrimitiveType())
1304 GEN_ERROR("Elemental type of a PackedType must be primitive");
1305 if (!isPowerOf2_32($2))
1306 GEN_ERROR("Vector length should be a power of 2!");
1307 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1311 | '{' TypeListI '}' { // Structure type?
1312 std::vector<const Type*> Elements;
1313 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1314 E = $2->end(); I != E; ++I)
1315 Elements.push_back(*I);
1317 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1321 | '{' '}' { // Empty structure type?
1322 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1325 | UpRTypes '*' { // Pointer type?
1326 if (*$1 == Type::LabelTy)
1327 GEN_ERROR("Cannot form a pointer to a basic block");
1328 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1333 // TypeList - Used for struct declarations and as a basis for function type
1334 // declaration type lists
1336 TypeListI : UpRTypes {
1337 $$ = new std::list<PATypeHolder>();
1338 $$->push_back(*$1); delete $1;
1341 | TypeListI ',' UpRTypes {
1342 ($$=$1)->push_back(*$3); delete $3;
1346 // ArgTypeList - List of types for a function type declaration...
1347 ArgTypeListI : TypeListI
1348 | TypeListI ',' DOTDOTDOT {
1349 ($$=$1)->push_back(Type::VoidTy);
1353 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1357 $$ = new std::list<PATypeHolder>();
1361 // ConstVal - The various declarations that go into the constant pool. This
1362 // production is used ONLY to represent constants that show up AFTER a 'const',
1363 // 'constant' or 'global' token at global scope. Constants that can be inlined
1364 // into other expressions (such as integers and constexprs) are handled by the
1365 // ResolvedVal, ValueRef and ConstValueRef productions.
1367 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1368 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1370 GEN_ERROR("Cannot make array constant with type: '" +
1371 (*$1)->getDescription() + "'!");
1372 const Type *ETy = ATy->getElementType();
1373 int NumElements = ATy->getNumElements();
1375 // Verify that we have the correct size...
1376 if (NumElements != -1 && NumElements != (int)$3->size())
1377 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1378 utostr($3->size()) + " arguments, but has size of " +
1379 itostr(NumElements) + "!");
1381 // Verify all elements are correct type!
1382 for (unsigned i = 0; i < $3->size(); i++) {
1383 if (ETy != (*$3)[i]->getType())
1384 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1385 ETy->getDescription() +"' as required!\nIt is of type '"+
1386 (*$3)[i]->getType()->getDescription() + "'.");
1389 $$ = ConstantArray::get(ATy, *$3);
1390 delete $1; delete $3;
1394 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1396 GEN_ERROR("Cannot make array constant with type: '" +
1397 (*$1)->getDescription() + "'!");
1399 int NumElements = ATy->getNumElements();
1400 if (NumElements != -1 && NumElements != 0)
1401 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1402 " arguments, but has size of " + itostr(NumElements) +"!");
1403 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1407 | Types 'c' STRINGCONSTANT {
1408 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1410 GEN_ERROR("Cannot make array constant with type: '" +
1411 (*$1)->getDescription() + "'!");
1413 int NumElements = ATy->getNumElements();
1414 const Type *ETy = ATy->getElementType();
1415 char *EndStr = UnEscapeLexed($3, true);
1416 if (NumElements != -1 && NumElements != (EndStr-$3))
1417 GEN_ERROR("Can't build string constant of size " +
1418 itostr((int)(EndStr-$3)) +
1419 " when array has size " + itostr(NumElements) + "!");
1420 std::vector<Constant*> Vals;
1421 if (ETy == Type::SByteTy) {
1422 for (signed char *C = (signed char *)$3; C != (signed char *)EndStr; ++C)
1423 Vals.push_back(ConstantInt::get(ETy, *C));
1424 } else if (ETy == Type::UByteTy) {
1425 for (unsigned char *C = (unsigned char *)$3;
1426 C != (unsigned char*)EndStr; ++C)
1427 Vals.push_back(ConstantInt::get(ETy, *C));
1430 GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1433 $$ = ConstantArray::get(ATy, Vals);
1437 | Types '<' ConstVector '>' { // Nonempty unsized arr
1438 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1440 GEN_ERROR("Cannot make packed constant with type: '" +
1441 (*$1)->getDescription() + "'!");
1442 const Type *ETy = PTy->getElementType();
1443 int NumElements = PTy->getNumElements();
1445 // Verify that we have the correct size...
1446 if (NumElements != -1 && NumElements != (int)$3->size())
1447 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1448 utostr($3->size()) + " arguments, but has size of " +
1449 itostr(NumElements) + "!");
1451 // Verify all elements are correct type!
1452 for (unsigned i = 0; i < $3->size(); i++) {
1453 if (ETy != (*$3)[i]->getType())
1454 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1455 ETy->getDescription() +"' as required!\nIt is of type '"+
1456 (*$3)[i]->getType()->getDescription() + "'.");
1459 $$ = ConstantPacked::get(PTy, *$3);
1460 delete $1; delete $3;
1463 | Types '{' ConstVector '}' {
1464 const StructType *STy = dyn_cast<StructType>($1->get());
1466 GEN_ERROR("Cannot make struct constant with type: '" +
1467 (*$1)->getDescription() + "'!");
1469 if ($3->size() != STy->getNumContainedTypes())
1470 GEN_ERROR("Illegal number of initializers for structure type!");
1472 // Check to ensure that constants are compatible with the type initializer!
1473 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1474 if ((*$3)[i]->getType() != STy->getElementType(i))
1475 GEN_ERROR("Expected type '" +
1476 STy->getElementType(i)->getDescription() +
1477 "' for element #" + utostr(i) +
1478 " of structure initializer!");
1480 $$ = ConstantStruct::get(STy, *$3);
1481 delete $1; delete $3;
1485 const StructType *STy = dyn_cast<StructType>($1->get());
1487 GEN_ERROR("Cannot make struct constant with type: '" +
1488 (*$1)->getDescription() + "'!");
1490 if (STy->getNumContainedTypes() != 0)
1491 GEN_ERROR("Illegal number of initializers for structure type!");
1493 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1498 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1500 GEN_ERROR("Cannot make null pointer constant with type: '" +
1501 (*$1)->getDescription() + "'!");
1503 $$ = ConstantPointerNull::get(PTy);
1508 $$ = UndefValue::get($1->get());
1512 | Types SymbolicValueRef {
1513 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1515 GEN_ERROR("Global const reference must be a pointer type!");
1517 // ConstExprs can exist in the body of a function, thus creating
1518 // GlobalValues whenever they refer to a variable. Because we are in
1519 // the context of a function, getValNonImprovising will search the functions
1520 // symbol table instead of the module symbol table for the global symbol,
1521 // which throws things all off. To get around this, we just tell
1522 // getValNonImprovising that we are at global scope here.
1524 Function *SavedCurFn = CurFun.CurrentFunction;
1525 CurFun.CurrentFunction = 0;
1527 Value *V = getValNonImprovising(Ty, $2);
1530 CurFun.CurrentFunction = SavedCurFn;
1532 // If this is an initializer for a constant pointer, which is referencing a
1533 // (currently) undefined variable, create a stub now that shall be replaced
1534 // in the future with the right type of variable.
1537 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1538 const PointerType *PT = cast<PointerType>(Ty);
1540 // First check to see if the forward references value is already created!
1541 PerModuleInfo::GlobalRefsType::iterator I =
1542 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1544 if (I != CurModule.GlobalRefs.end()) {
1545 V = I->second; // Placeholder already exists, use it...
1549 if ($2.Type == ValID::NameVal) Name = $2.Name;
1551 // Create the forward referenced global.
1553 if (const FunctionType *FTy =
1554 dyn_cast<FunctionType>(PT->getElementType())) {
1555 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1556 CurModule.CurrentModule);
1558 GV = new GlobalVariable(PT->getElementType(), false,
1559 GlobalValue::ExternalLinkage, 0,
1560 Name, CurModule.CurrentModule);
1563 // Keep track of the fact that we have a forward ref to recycle it
1564 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1569 $$ = cast<GlobalValue>(V);
1570 delete $1; // Free the type handle
1574 if ($1->get() != $2->getType())
1575 GEN_ERROR("Mismatched types for constant expression!");
1580 | Types ZEROINITIALIZER {
1581 const Type *Ty = $1->get();
1582 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1583 GEN_ERROR("Cannot create a null initialized value of this type!");
1584 $$ = Constant::getNullValue(Ty);
1588 | SIntType EINT64VAL { // integral constants
1589 if (!ConstantInt::isValueValidForType($1, $2))
1590 GEN_ERROR("Constant value doesn't fit in type!");
1591 $$ = ConstantInt::get($1, $2);
1594 | UIntType EUINT64VAL { // integral constants
1595 if (!ConstantInt::isValueValidForType($1, $2))
1596 GEN_ERROR("Constant value doesn't fit in type!");
1597 $$ = ConstantInt::get($1, $2);
1600 | BOOL TRUETOK { // Boolean constants
1601 $$ = ConstantBool::getTrue();
1604 | BOOL FALSETOK { // Boolean constants
1605 $$ = ConstantBool::getFalse();
1608 | FPType FPVAL { // Float & Double constants
1609 if (!ConstantFP::isValueValidForType($1, $2))
1610 GEN_ERROR("Floating point constant invalid for type!!");
1611 $$ = ConstantFP::get($1, $2);
1616 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1618 const Type *Ty = $5->get();
1619 if (!Val->getType()->isFirstClassType())
1620 GEN_ERROR("cast constant expression from a non-primitive type: '" +
1621 Val->getType()->getDescription() + "'!");
1622 if (!Ty->isFirstClassType())
1623 GEN_ERROR("cast constant expression to a non-primitive type: '" +
1624 Ty->getDescription() + "'!");
1625 $$ = ConstantExpr::getCast($1, $3, $5->get());
1628 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1629 if (!isa<PointerType>($3->getType()))
1630 GEN_ERROR("GetElementPtr requires a pointer operand!");
1632 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1633 // indices to uint struct indices for compatibility.
1634 generic_gep_type_iterator<std::vector<Value*>::iterator>
1635 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1636 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1637 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1638 if (isa<StructType>(*GTI)) // Only change struct indices
1639 if (ConstantInt *CUI = dyn_cast<ConstantInt>((*$4)[i]))
1640 if (CUI->getType() == Type::UByteTy)
1641 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1644 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1646 GEN_ERROR("Index list invalid for constant getelementptr!");
1648 std::vector<Constant*> IdxVec;
1649 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1650 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1651 IdxVec.push_back(C);
1653 GEN_ERROR("Indices to constant getelementptr must be constants!");
1657 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1660 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1661 if ($3->getType() != Type::BoolTy)
1662 GEN_ERROR("Select condition must be of boolean type!");
1663 if ($5->getType() != $7->getType())
1664 GEN_ERROR("Select operand types must match!");
1665 $$ = ConstantExpr::getSelect($3, $5, $7);
1668 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1669 if ($3->getType() != $5->getType())
1670 GEN_ERROR("Binary operator types must match!");
1673 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1674 // To retain backward compatibility with these early compilers, we emit a
1675 // cast to the appropriate integer type automatically if we are in the
1676 // broken case. See PR424 for more information.
1677 if (!isa<PointerType>($3->getType())) {
1678 $$ = ConstantExpr::get($1, $3, $5);
1680 const Type *IntPtrTy = 0;
1681 switch (CurModule.CurrentModule->getPointerSize()) {
1682 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1683 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1684 default: GEN_ERROR("invalid pointer binary constant expr!");
1686 $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1687 ConstantExpr::getCast($5, IntPtrTy));
1688 $$ = ConstantExpr::getCast($$, $3->getType());
1692 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1693 if ($3->getType() != $5->getType())
1694 GEN_ERROR("Logical operator types must match!");
1695 if (!$3->getType()->isIntegral()) {
1696 if (!isa<PackedType>($3->getType()) ||
1697 !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1698 GEN_ERROR("Logical operator requires integral operands!");
1700 $$ = ConstantExpr::get($1, $3, $5);
1703 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1704 if ($3->getType() != $5->getType())
1705 GEN_ERROR("setcc operand types must match!");
1706 $$ = ConstantExpr::get($1, $3, $5);
1709 | ICMP '(' IPredicates ',' ConstVal ',' ConstVal ')' {
1710 if ($5->getType() != $7->getType())
1711 GEN_ERROR("icmp operand types must match!");
1712 $$ = ConstantExpr::getICmp($3, $5, $7);
1714 | FCMP '(' FPredicates ',' ConstVal ',' ConstVal ')' {
1715 if ($5->getType() != $7->getType())
1716 GEN_ERROR("fcmp operand types must match!");
1717 $$ = ConstantExpr::getFCmp($3, $5, $7);
1719 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1720 if ($5->getType() != Type::UByteTy)
1721 GEN_ERROR("Shift count for shift constant must be unsigned byte!");
1722 if (!$3->getType()->isInteger())
1723 GEN_ERROR("Shift constant expression requires integer operand!");
1725 $$ = ConstantExpr::get($1, $3, $5);
1728 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1729 if (!ExtractElementInst::isValidOperands($3, $5))
1730 GEN_ERROR("Invalid extractelement operands!");
1731 $$ = ConstantExpr::getExtractElement($3, $5);
1734 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1735 if (!InsertElementInst::isValidOperands($3, $5, $7))
1736 GEN_ERROR("Invalid insertelement operands!");
1737 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1740 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1741 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1742 GEN_ERROR("Invalid shufflevector operands!");
1743 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1748 // ConstVector - A list of comma separated constants.
1749 ConstVector : ConstVector ',' ConstVal {
1750 ($$ = $1)->push_back($3);
1754 $$ = new std::vector<Constant*>();
1760 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1761 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1764 //===----------------------------------------------------------------------===//
1765 // Rules to match Modules
1766 //===----------------------------------------------------------------------===//
1768 // Module rule: Capture the result of parsing the whole file into a result
1771 Module : FunctionList {
1772 $$ = ParserResult = $1;
1773 CurModule.ModuleDone();
1777 // FunctionList - A list of functions, preceeded by a constant pool.
1779 FunctionList : FunctionList Function {
1781 CurFun.FunctionDone();
1784 | FunctionList FunctionProto {
1788 | FunctionList MODULE ASM_TOK AsmBlock {
1792 | FunctionList IMPLEMENTATION {
1797 $$ = CurModule.CurrentModule;
1798 // Emit an error if there are any unresolved types left.
1799 if (!CurModule.LateResolveTypes.empty()) {
1800 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1801 if (DID.Type == ValID::NameVal) {
1802 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1804 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1810 // ConstPool - Constants with optional names assigned to them.
1811 ConstPool : ConstPool OptAssign TYPE TypesV {
1812 // Eagerly resolve types. This is not an optimization, this is a
1813 // requirement that is due to the fact that we could have this:
1815 // %list = type { %list * }
1816 // %list = type { %list * } ; repeated type decl
1818 // If types are not resolved eagerly, then the two types will not be
1819 // determined to be the same type!
1821 ResolveTypeTo($2, *$4);
1823 if (!setTypeName(*$4, $2) && !$2) {
1825 // If this is a named type that is not a redefinition, add it to the slot
1827 CurModule.Types.push_back(*$4);
1833 | ConstPool FunctionProto { // Function prototypes can be in const pool
1836 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
1839 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1841 GEN_ERROR("Global value initializer is not a constant!");
1842 CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1844 } GlobalVarAttributes {
1847 | ConstPool OptAssign EXTERNAL GlobalType Types {
1848 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1851 } GlobalVarAttributes {
1855 | ConstPool OptAssign DLLIMPORT GlobalType Types {
1856 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, *$5, 0);
1859 } GlobalVarAttributes {
1863 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
1865 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, *$5, 0);
1868 } GlobalVarAttributes {
1872 | ConstPool TARGET TargetDefinition {
1875 | ConstPool DEPLIBS '=' LibrariesDefinition {
1878 | /* empty: end of list */ {
1882 AsmBlock : STRINGCONSTANT {
1883 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1884 char *EndStr = UnEscapeLexed($1, true);
1885 std::string NewAsm($1, EndStr);
1888 if (AsmSoFar.empty())
1889 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1891 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1895 BigOrLittle : BIG { $$ = Module::BigEndian; };
1896 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1898 TargetDefinition : ENDIAN '=' BigOrLittle {
1899 CurModule.CurrentModule->setEndianness($3);
1902 | POINTERSIZE '=' EUINT64VAL {
1904 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1906 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1908 GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1911 | TRIPLE '=' STRINGCONSTANT {
1912 CurModule.CurrentModule->setTargetTriple($3);
1915 | DATALAYOUT '=' STRINGCONSTANT {
1916 CurModule.CurrentModule->setDataLayout($3);
1920 LibrariesDefinition : '[' LibList ']';
1922 LibList : LibList ',' STRINGCONSTANT {
1923 CurModule.CurrentModule->addLibrary($3);
1928 CurModule.CurrentModule->addLibrary($1);
1932 | /* empty: end of list */ {
1937 //===----------------------------------------------------------------------===//
1938 // Rules to match Function Headers
1939 //===----------------------------------------------------------------------===//
1941 Name : VAR_ID | STRINGCONSTANT;
1942 OptName : Name | /*empty*/ { $$ = 0; };
1944 ArgVal : Types OptName {
1945 if (*$1 == Type::VoidTy)
1946 GEN_ERROR("void typed arguments are invalid!");
1947 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1951 ArgListH : ArgListH ',' ArgVal {
1958 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1964 ArgList : ArgListH {
1968 | ArgListH ',' DOTDOTDOT {
1970 $$->push_back(std::pair<PATypeHolder*,
1971 char*>(new PATypeHolder(Type::VoidTy), 0));
1975 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1976 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1984 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')'
1985 OptSection OptAlign {
1987 std::string FunctionName($3);
1988 free($3); // Free strdup'd memory!
1990 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1991 GEN_ERROR("LLVM functions cannot return aggregate types!");
1993 std::vector<const Type*> ParamTypeList;
1994 if ($5) { // If there are arguments...
1995 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1996 I != $5->end(); ++I)
1997 ParamTypeList.push_back(I->first->get());
2000 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2001 if (isVarArg) ParamTypeList.pop_back();
2003 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
2004 const PointerType *PFT = PointerType::get(FT);
2008 if (!FunctionName.empty()) {
2009 ID = ValID::create((char*)FunctionName.c_str());
2011 ID = ValID::create((int)CurModule.Values[PFT].size());
2015 // See if this function was forward referenced. If so, recycle the object.
2016 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2017 // Move the function to the end of the list, from whereever it was
2018 // previously inserted.
2019 Fn = cast<Function>(FWRef);
2020 CurModule.CurrentModule->getFunctionList().remove(Fn);
2021 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2022 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2023 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2024 // If this is the case, either we need to be a forward decl, or it needs
2026 if (!CurFun.isDeclare && !Fn->isExternal())
2027 GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
2029 // Make sure to strip off any argument names so we can't get conflicts.
2030 if (Fn->isExternal())
2031 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2034 } else { // Not already defined?
2035 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2036 CurModule.CurrentModule);
2038 InsertValue(Fn, CurModule.Values);
2041 CurFun.FunctionStart(Fn);
2043 if (CurFun.isDeclare) {
2044 // If we have declaration, always overwrite linkage. This will allow us to
2045 // correctly handle cases, when pointer to function is passed as argument to
2046 // another function.
2047 Fn->setLinkage(CurFun.Linkage);
2049 Fn->setCallingConv($1);
2050 Fn->setAlignment($8);
2056 // Add all of the arguments we parsed to the function...
2057 if ($5) { // Is null if empty...
2058 if (isVarArg) { // Nuke the last entry
2059 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
2060 "Not a varargs marker!");
2061 delete $5->back().first;
2062 $5->pop_back(); // Delete the last entry
2064 Function::arg_iterator ArgIt = Fn->arg_begin();
2065 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
2066 I != $5->end(); ++I, ++ArgIt) {
2067 delete I->first; // Delete the typeholder...
2069 setValueName(ArgIt, I->second); // Insert arg into symtab...
2074 delete $5; // We're now done with the argument list
2079 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2081 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
2082 $$ = CurFun.CurrentFunction;
2084 // Make sure that we keep track of the linkage type even if there was a
2085 // previous "declare".
2089 END : ENDTOK | '}'; // Allow end of '}' to end a function
2091 Function : BasicBlockList END {
2096 FnDeclareLinkage: /*default*/ |
2097 DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; } |
2098 EXTERN_WEAK { CurFun.Linkage = GlobalValue::ExternalWeakLinkage; };
2100 FunctionProto : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2101 $$ = CurFun.CurrentFunction;
2102 CurFun.FunctionDone();
2106 //===----------------------------------------------------------------------===//
2107 // Rules to match Basic Blocks
2108 //===----------------------------------------------------------------------===//
2110 OptSideEffect : /* empty */ {
2119 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2120 $$ = ValID::create($1);
2124 $$ = ValID::create($1);
2127 | FPVAL { // Perhaps it's an FP constant?
2128 $$ = ValID::create($1);
2132 $$ = ValID::create(ConstantBool::getTrue());
2136 $$ = ValID::create(ConstantBool::getFalse());
2140 $$ = ValID::createNull();
2144 $$ = ValID::createUndef();
2147 | ZEROINITIALIZER { // A vector zero constant.
2148 $$ = ValID::createZeroInit();
2151 | '<' ConstVector '>' { // Nonempty unsized packed vector
2152 const Type *ETy = (*$2)[0]->getType();
2153 int NumElements = $2->size();
2155 PackedType* pt = PackedType::get(ETy, NumElements);
2156 PATypeHolder* PTy = new PATypeHolder(
2164 // Verify all elements are correct type!
2165 for (unsigned i = 0; i < $2->size(); i++) {
2166 if (ETy != (*$2)[i]->getType())
2167 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2168 ETy->getDescription() +"' as required!\nIt is of type '" +
2169 (*$2)[i]->getType()->getDescription() + "'.");
2172 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2173 delete PTy; delete $2;
2177 $$ = ValID::create($1);
2180 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2181 char *End = UnEscapeLexed($3, true);
2182 std::string AsmStr = std::string($3, End);
2183 End = UnEscapeLexed($5, true);
2184 std::string Constraints = std::string($5, End);
2185 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2191 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2194 SymbolicValueRef : INTVAL { // Is it an integer reference...?
2195 $$ = ValID::create($1);
2198 | Name { // Is it a named reference...?
2199 $$ = ValID::create($1);
2203 // ValueRef - A reference to a definition... either constant or symbolic
2204 ValueRef : SymbolicValueRef | ConstValueRef;
2207 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2208 // type immediately preceeds the value reference, and allows complex constant
2209 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2210 ResolvedVal : Types ValueRef {
2211 $$ = getVal(*$1, $2); delete $1;
2215 BasicBlockList : BasicBlockList BasicBlock {
2219 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2225 // Basic blocks are terminated by branching instructions:
2226 // br, br/cc, switch, ret
2228 BasicBlock : InstructionList OptAssign BBTerminatorInst {
2229 setValueName($3, $2);
2233 $1->getInstList().push_back($3);
2239 InstructionList : InstructionList Inst {
2240 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2241 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2242 if (CI2->getParent() == 0)
2243 $1->getInstList().push_back(CI2);
2244 $1->getInstList().push_back($2);
2249 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2252 // Make sure to move the basic block to the correct location in the
2253 // function, instead of leaving it inserted wherever it was first
2255 Function::BasicBlockListType &BBL =
2256 CurFun.CurrentFunction->getBasicBlockList();
2257 BBL.splice(BBL.end(), BBL, $$);
2261 $$ = CurBB = getBBVal(ValID::create($1), true);
2264 // Make sure to move the basic block to the correct location in the
2265 // function, instead of leaving it inserted wherever it was first
2267 Function::BasicBlockListType &BBL =
2268 CurFun.CurrentFunction->getBasicBlockList();
2269 BBL.splice(BBL.end(), BBL, $$);
2273 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2274 $$ = new ReturnInst($2);
2277 | RET VOID { // Return with no result...
2278 $$ = new ReturnInst();
2281 | BR LABEL ValueRef { // Unconditional Branch...
2282 BasicBlock* tmpBB = getBBVal($3);
2284 $$ = new BranchInst(tmpBB);
2285 } // Conditional Branch...
2286 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2287 BasicBlock* tmpBBA = getBBVal($6);
2289 BasicBlock* tmpBBB = getBBVal($9);
2291 Value* tmpVal = getVal(Type::BoolTy, $3);
2293 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2295 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2296 Value* tmpVal = getVal($2, $3);
2298 BasicBlock* tmpBB = getBBVal($6);
2300 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2303 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2305 for (; I != E; ++I) {
2306 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2307 S->addCase(CI, I->second);
2309 GEN_ERROR("Switch case is constant, but not a simple integer!");
2314 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2315 Value* tmpVal = getVal($2, $3);
2317 BasicBlock* tmpBB = getBBVal($6);
2319 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2323 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2324 TO LABEL ValueRef UNWIND LABEL ValueRef {
2325 const PointerType *PFTy;
2326 const FunctionType *Ty;
2328 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2329 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2330 // Pull out the types of all of the arguments...
2331 std::vector<const Type*> ParamTypes;
2333 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2335 ParamTypes.push_back((*I)->getType());
2338 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2339 if (isVarArg) ParamTypes.pop_back();
2341 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2342 PFTy = PointerType::get(Ty);
2345 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2347 BasicBlock *Normal = getBBVal($10);
2349 BasicBlock *Except = getBBVal($13);
2352 // Create the call node...
2353 if (!$6) { // Has no arguments?
2354 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2355 } else { // Has arguments?
2356 // Loop through FunctionType's arguments and ensure they are specified
2359 FunctionType::param_iterator I = Ty->param_begin();
2360 FunctionType::param_iterator E = Ty->param_end();
2361 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2363 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2364 if ((*ArgI)->getType() != *I)
2365 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2366 (*I)->getDescription() + "'!");
2368 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2369 GEN_ERROR("Invalid number of parameters detected!");
2371 $$ = new InvokeInst(V, Normal, Except, *$6);
2373 cast<InvokeInst>($$)->setCallingConv($2);
2380 $$ = new UnwindInst();
2384 $$ = new UnreachableInst();
2390 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2392 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2395 GEN_ERROR("May only switch on a constant pool value!");
2397 BasicBlock* tmpBB = getBBVal($6);
2399 $$->push_back(std::make_pair(V, tmpBB));
2401 | IntType ConstValueRef ',' LABEL ValueRef {
2402 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2403 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2407 GEN_ERROR("May only switch on a constant pool value!");
2409 BasicBlock* tmpBB = getBBVal($5);
2411 $$->push_back(std::make_pair(V, tmpBB));
2414 Inst : OptAssign InstVal {
2415 // Is this definition named?? if so, assign the name...
2416 setValueName($2, $1);
2423 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2424 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2425 Value* tmpVal = getVal(*$1, $3);
2427 BasicBlock* tmpBB = getBBVal($5);
2429 $$->push_back(std::make_pair(tmpVal, tmpBB));
2432 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2434 Value* tmpVal = getVal($1->front().first->getType(), $4);
2436 BasicBlock* tmpBB = getBBVal($6);
2438 $1->push_back(std::make_pair(tmpVal, tmpBB));
2442 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2443 $$ = new std::vector<Value*>();
2446 | ValueRefList ',' ResolvedVal {
2452 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2453 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2455 OptTailCall : TAIL CALL {
2464 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2465 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2466 !isa<PackedType>((*$2).get()))
2468 "Arithmetic operator requires integer, FP, or packed operands!");
2469 if (isa<PackedType>((*$2).get()) &&
2470 ($1 == Instruction::URem ||
2471 $1 == Instruction::SRem ||
2472 $1 == Instruction::FRem))
2473 GEN_ERROR("U/S/FRem not supported on packed types!");
2474 Value* val1 = getVal(*$2, $3);
2476 Value* val2 = getVal(*$2, $5);
2478 $$ = BinaryOperator::create($1, val1, val2);
2480 GEN_ERROR("binary operator returned null!");
2483 | LogicalOps Types ValueRef ',' ValueRef {
2484 if (!(*$2)->isIntegral()) {
2485 if (!isa<PackedType>($2->get()) ||
2486 !cast<PackedType>($2->get())->getElementType()->isIntegral())
2487 GEN_ERROR("Logical operator requires integral operands!");
2489 Value* tmpVal1 = getVal(*$2, $3);
2491 Value* tmpVal2 = getVal(*$2, $5);
2493 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2495 GEN_ERROR("binary operator returned null!");
2498 | SetCondOps Types ValueRef ',' ValueRef {
2499 if(isa<PackedType>((*$2).get())) {
2501 "PackedTypes currently not supported in setcc instructions!");
2503 Value* tmpVal1 = getVal(*$2, $3);
2505 Value* tmpVal2 = getVal(*$2, $5);
2507 $$ = new SetCondInst($1, tmpVal1, tmpVal2);
2509 GEN_ERROR("binary operator returned null!");
2512 | ICMP IPredicates Types ValueRef ',' ValueRef {
2513 if (isa<PackedType>((*$3).get()))
2514 GEN_ERROR("Packed types not supported by icmp instruction");
2515 Value* tmpVal1 = getVal(*$3, $4);
2517 Value* tmpVal2 = getVal(*$3, $6);
2519 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2521 GEN_ERROR("icmp operator returned null!");
2523 | FCMP FPredicates Types ValueRef ',' ValueRef {
2524 if (isa<PackedType>((*$3).get()))
2525 GEN_ERROR("Packed types not supported by fcmp instruction");
2526 Value* tmpVal1 = getVal(*$3, $4);
2528 Value* tmpVal2 = getVal(*$3, $6);
2530 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2532 GEN_ERROR("fcmp operator returned null!");
2535 llvm_cerr << "WARNING: Use of eliminated 'not' instruction:"
2536 << " Replacing with 'xor'.\n";
2538 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2540 GEN_ERROR("Expected integral type for not instruction!");
2542 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2544 GEN_ERROR("Could not create a xor instruction!");
2547 | ShiftOps ResolvedVal ',' ResolvedVal {
2548 if ($4->getType() != Type::UByteTy)
2549 GEN_ERROR("Shift amount must be ubyte!");
2550 if (!$2->getType()->isInteger())
2551 GEN_ERROR("Shift constant expression requires integer operand!");
2553 $$ = new ShiftInst($1, $2, $4);
2556 | CastOps ResolvedVal TO Types {
2558 const Type* Ty = $4->get();
2559 if (!Val->getType()->isFirstClassType())
2560 GEN_ERROR("cast from a non-primitive type: '" +
2561 Val->getType()->getDescription() + "'!");
2562 if (!Ty->isFirstClassType())
2563 GEN_ERROR("cast to a non-primitive type: '" + Ty->getDescription() +"'!");
2564 $$ = CastInst::create($1, $2, $4->get());
2567 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2568 if ($2->getType() != Type::BoolTy)
2569 GEN_ERROR("select condition must be boolean!");
2570 if ($4->getType() != $6->getType())
2571 GEN_ERROR("select value types should match!");
2572 $$ = new SelectInst($2, $4, $6);
2575 | VAARG ResolvedVal ',' Types {
2577 $$ = new VAArgInst($2, *$4);
2581 | VAARG_old ResolvedVal ',' Types {
2582 ObsoleteVarArgs = true;
2583 const Type* ArgTy = $2->getType();
2584 Function* NF = CurModule.CurrentModule->
2585 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2588 //foo = alloca 1 of t
2592 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2593 CurBB->getInstList().push_back(foo);
2594 CallInst* bar = new CallInst(NF, $2);
2595 CurBB->getInstList().push_back(bar);
2596 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2597 $$ = new VAArgInst(foo, *$4);
2601 | VANEXT_old ResolvedVal ',' Types {
2602 ObsoleteVarArgs = true;
2603 const Type* ArgTy = $2->getType();
2604 Function* NF = CurModule.CurrentModule->
2605 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2607 //b = vanext a, t ->
2608 //foo = alloca 1 of t
2611 //tmp = vaarg foo, t
2613 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2614 CurBB->getInstList().push_back(foo);
2615 CallInst* bar = new CallInst(NF, $2);
2616 CurBB->getInstList().push_back(bar);
2617 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2618 Instruction* tmp = new VAArgInst(foo, *$4);
2619 CurBB->getInstList().push_back(tmp);
2620 $$ = new LoadInst(foo);
2624 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2625 if (!ExtractElementInst::isValidOperands($2, $4))
2626 GEN_ERROR("Invalid extractelement operands!");
2627 $$ = new ExtractElementInst($2, $4);
2630 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2631 if (!InsertElementInst::isValidOperands($2, $4, $6))
2632 GEN_ERROR("Invalid insertelement operands!");
2633 $$ = new InsertElementInst($2, $4, $6);
2636 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2637 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2638 GEN_ERROR("Invalid shufflevector operands!");
2639 $$ = new ShuffleVectorInst($2, $4, $6);
2643 const Type *Ty = $2->front().first->getType();
2644 if (!Ty->isFirstClassType())
2645 GEN_ERROR("PHI node operands must be of first class type!");
2646 $$ = new PHINode(Ty);
2647 ((PHINode*)$$)->reserveOperandSpace($2->size());
2648 while ($2->begin() != $2->end()) {
2649 if ($2->front().first->getType() != Ty)
2650 GEN_ERROR("All elements of a PHI node must be of the same type!");
2651 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2654 delete $2; // Free the list...
2657 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2658 const PointerType *PFTy = 0;
2659 const FunctionType *Ty = 0;
2661 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2662 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2663 // Pull out the types of all of the arguments...
2664 std::vector<const Type*> ParamTypes;
2666 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2668 ParamTypes.push_back((*I)->getType());
2671 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2672 if (isVarArg) ParamTypes.pop_back();
2674 if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2675 GEN_ERROR("LLVM functions cannot return aggregate types!");
2677 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2678 PFTy = PointerType::get(Ty);
2681 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2684 // Create the call node...
2685 if (!$6) { // Has no arguments?
2686 // Make sure no arguments is a good thing!
2687 if (Ty->getNumParams() != 0)
2688 GEN_ERROR("No arguments passed to a function that "
2689 "expects arguments!");
2691 $$ = new CallInst(V, std::vector<Value*>());
2692 } else { // Has arguments?
2693 // Loop through FunctionType's arguments and ensure they are specified
2696 FunctionType::param_iterator I = Ty->param_begin();
2697 FunctionType::param_iterator E = Ty->param_end();
2698 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2700 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2701 if ((*ArgI)->getType() != *I)
2702 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2703 (*I)->getDescription() + "'!");
2705 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2706 GEN_ERROR("Invalid number of parameters detected!");
2708 $$ = new CallInst(V, *$6);
2710 cast<CallInst>($$)->setTailCall($1);
2711 cast<CallInst>($$)->setCallingConv($2);
2722 // IndexList - List of indices for GEP based instructions...
2723 IndexList : ',' ValueRefList {
2727 $$ = new std::vector<Value*>();
2731 OptVolatile : VOLATILE {
2742 MemoryInst : MALLOC Types OptCAlign {
2743 $$ = new MallocInst(*$2, 0, $3);
2747 | MALLOC Types ',' UINT ValueRef OptCAlign {
2748 Value* tmpVal = getVal($4, $5);
2750 $$ = new MallocInst(*$2, tmpVal, $6);
2753 | ALLOCA Types OptCAlign {
2754 $$ = new AllocaInst(*$2, 0, $3);
2758 | ALLOCA Types ',' UINT ValueRef OptCAlign {
2759 Value* tmpVal = getVal($4, $5);
2761 $$ = new AllocaInst(*$2, tmpVal, $6);
2764 | FREE ResolvedVal {
2765 if (!isa<PointerType>($2->getType()))
2766 GEN_ERROR("Trying to free nonpointer type " +
2767 $2->getType()->getDescription() + "!");
2768 $$ = new FreeInst($2);
2772 | OptVolatile LOAD Types ValueRef {
2773 if (!isa<PointerType>($3->get()))
2774 GEN_ERROR("Can't load from nonpointer type: " +
2775 (*$3)->getDescription());
2776 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2777 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2778 (*$3)->getDescription());
2779 Value* tmpVal = getVal(*$3, $4);
2781 $$ = new LoadInst(tmpVal, "", $1);
2784 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2785 const PointerType *PT = dyn_cast<PointerType>($5->get());
2787 GEN_ERROR("Can't store to a nonpointer type: " +
2788 (*$5)->getDescription());
2789 const Type *ElTy = PT->getElementType();
2790 if (ElTy != $3->getType())
2791 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2792 "' into space of type '" + ElTy->getDescription() + "'!");
2794 Value* tmpVal = getVal(*$5, $6);
2796 $$ = new StoreInst($3, tmpVal, $1);
2799 | GETELEMENTPTR Types ValueRef IndexList {
2800 if (!isa<PointerType>($2->get()))
2801 GEN_ERROR("getelementptr insn requires pointer operand!");
2803 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2804 // indices to uint struct indices for compatibility.
2805 generic_gep_type_iterator<std::vector<Value*>::iterator>
2806 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2807 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2808 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2809 if (isa<StructType>(*GTI)) // Only change struct indices
2810 if (ConstantInt *CUI = dyn_cast<ConstantInt>((*$4)[i]))
2811 if (CUI->getType() == Type::UByteTy)
2812 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2814 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2815 GEN_ERROR("Invalid getelementptr indices for type '" +
2816 (*$2)->getDescription()+ "'!");
2817 Value* tmpVal = getVal(*$2, $3);
2819 $$ = new GetElementPtrInst(tmpVal, *$4);
2827 void llvm::GenerateError(const std::string &message, int LineNo) {
2828 if (LineNo == -1) LineNo = llvmAsmlineno;
2829 // TODO: column number in exception
2831 TheParseError->setError(CurFilename, message, LineNo);
2835 int yyerror(const char *ErrorMsg) {
2837 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2838 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2839 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2840 if (yychar == YYEMPTY || yychar == 0)
2841 errMsg += "end-of-file.";
2843 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2844 GenerateError(errMsg);