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/Instructions.h"
17 #include "llvm/Module.h"
18 #include "llvm/SymbolTable.h"
19 #include "llvm/Support/GetElementPtrTypeIterator.h"
20 #include "llvm/ADT/STLExtras.h"
26 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
27 int yylex(); // declaration" of xxx warnings.
31 std::string CurFilename;
35 static Module *ParserResult;
37 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
38 // relating to upreferences in the input stream.
40 //#define DEBUG_UPREFS 1
42 #define UR_OUT(X) std::cerr << X
47 #define YYERROR_VERBOSE 1
49 // This contains info used when building the body of a function. It is
50 // destroyed when the function is completed.
52 typedef std::vector<Value *> ValueList; // Numbered defs
53 static void ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
54 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
56 static struct PerModuleInfo {
57 Module *CurrentModule;
58 std::map<const Type *, ValueList> Values; // Module level numbered definitions
59 std::map<const Type *,ValueList> LateResolveValues;
60 std::vector<PATypeHolder> Types;
61 std::map<ValID, PATypeHolder> LateResolveTypes;
63 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
64 /// how they were referenced and one which line of the input they came from so
65 /// that we can resolve them later and print error messages as appropriate.
66 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
68 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
69 // references to global values. Global values may be referenced before they
70 // are defined, and if so, the temporary object that they represent is held
71 // here. This is used for forward references of GlobalValues.
73 typedef std::map<std::pair<const PointerType *,
74 ValID>, GlobalValue*> GlobalRefsType;
75 GlobalRefsType GlobalRefs;
78 // If we could not resolve some functions at function compilation time
79 // (calls to functions before they are defined), resolve them now... Types
80 // are resolved when the constant pool has been completely parsed.
82 ResolveDefinitions(LateResolveValues);
84 // Check to make sure that all global value forward references have been
87 if (!GlobalRefs.empty()) {
88 std::string UndefinedReferences = "Unresolved global references exist:\n";
90 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
92 UndefinedReferences += " " + I->first.first->getDescription() + " " +
93 I->first.second.getName() + "\n";
95 ThrowException(UndefinedReferences);
98 Values.clear(); // Clear out function local definitions
104 // GetForwardRefForGlobal - Check to see if there is a forward reference
105 // for this global. If so, remove it from the GlobalRefs map and return it.
106 // If not, just return null.
107 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
108 // Check to see if there is a forward reference to this global variable...
109 // if there is, eliminate it and patch the reference to use the new def'n.
110 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
111 GlobalValue *Ret = 0;
112 if (I != GlobalRefs.end()) {
120 static struct PerFunctionInfo {
121 Function *CurrentFunction; // Pointer to current function being created
123 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
124 std::map<const Type*, ValueList> LateResolveValues;
125 bool isDeclare; // Is this function a forward declararation?
127 /// BBForwardRefs - When we see forward references to basic blocks, keep
128 /// track of them here.
129 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
130 std::vector<BasicBlock*> NumberedBlocks;
133 inline PerFunctionInfo() {
138 inline void FunctionStart(Function *M) {
143 void FunctionDone() {
144 NumberedBlocks.clear();
146 // Any forward referenced blocks left?
147 if (!BBForwardRefs.empty())
148 ThrowException("Undefined reference to label " +
149 BBForwardRefs.begin()->first->getName());
151 // Resolve all forward references now.
152 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
154 Values.clear(); // Clear out function local definitions
158 } CurFun; // Info for the current function...
160 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
163 //===----------------------------------------------------------------------===//
164 // Code to handle definitions of all the types
165 //===----------------------------------------------------------------------===//
167 static int InsertValue(Value *V,
168 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
169 if (V->hasName()) return -1; // Is this a numbered definition?
171 // Yes, insert the value into the value table...
172 ValueList &List = ValueTab[V->getType()];
174 return List.size()-1;
177 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
179 case ValID::NumberVal: // Is it a numbered definition?
180 // Module constants occupy the lowest numbered slots...
181 if ((unsigned)D.Num < CurModule.Types.size())
182 return CurModule.Types[(unsigned)D.Num];
184 case ValID::NameVal: // Is it a named definition?
185 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
186 D.destroy(); // Free old strdup'd memory...
191 ThrowException("Internal parser error: Invalid symbol type reference!");
194 // If we reached here, we referenced either a symbol that we don't know about
195 // or an id number that hasn't been read yet. We may be referencing something
196 // forward, so just create an entry to be resolved later and get to it...
198 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
201 if (inFunctionScope()) {
202 if (D.Type == ValID::NameVal)
203 ThrowException("Reference to an undefined type: '" + D.getName() + "'");
205 ThrowException("Reference to an undefined type: #" + itostr(D.Num));
208 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
209 if (I != CurModule.LateResolveTypes.end())
212 Type *Typ = OpaqueType::get();
213 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
217 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
218 SymbolTable &SymTab =
219 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
220 CurModule.CurrentModule->getSymbolTable();
221 return SymTab.lookup(Ty, Name);
224 // getValNonImprovising - Look up the value specified by the provided type and
225 // the provided ValID. If the value exists and has already been defined, return
226 // it. Otherwise return null.
228 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
229 if (isa<FunctionType>(Ty))
230 ThrowException("Functions are not values and "
231 "must be referenced as pointers");
234 case ValID::NumberVal: { // Is it a numbered definition?
235 unsigned Num = (unsigned)D.Num;
237 // Module constants occupy the lowest numbered slots...
238 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
239 if (VI != CurModule.Values.end()) {
240 if (Num < VI->second.size())
241 return VI->second[Num];
242 Num -= VI->second.size();
245 // Make sure that our type is within bounds
246 VI = CurFun.Values.find(Ty);
247 if (VI == CurFun.Values.end()) return 0;
249 // Check that the number is within bounds...
250 if (VI->second.size() <= Num) return 0;
252 return VI->second[Num];
255 case ValID::NameVal: { // Is it a named definition?
256 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
257 if (N == 0) return 0;
259 D.destroy(); // Free old strdup'd memory...
263 // Check to make sure that "Ty" is an integral type, and that our
264 // value will fit into the specified type...
265 case ValID::ConstSIntVal: // Is it a constant pool reference??
266 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
267 ThrowException("Signed integral constant '" +
268 itostr(D.ConstPool64) + "' is invalid for type '" +
269 Ty->getDescription() + "'!");
270 return ConstantSInt::get(Ty, D.ConstPool64);
272 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
273 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
274 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
275 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
276 "' is invalid or out of range!");
277 } else { // This is really a signed reference. Transmogrify.
278 return ConstantSInt::get(Ty, D.ConstPool64);
281 return ConstantUInt::get(Ty, D.UConstPool64);
284 case ValID::ConstFPVal: // Is it a floating point const pool reference?
285 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
286 ThrowException("FP constant invalid for type!!");
287 return ConstantFP::get(Ty, D.ConstPoolFP);
289 case ValID::ConstNullVal: // Is it a null value?
290 if (!isa<PointerType>(Ty))
291 ThrowException("Cannot create a a non pointer null!");
292 return ConstantPointerNull::get(cast<PointerType>(Ty));
294 case ValID::ConstUndefVal: // Is it an undef value?
295 return UndefValue::get(Ty);
297 case ValID::ConstantVal: // Fully resolved constant?
298 if (D.ConstantValue->getType() != Ty)
299 ThrowException("Constant expression type different from required type!");
300 return D.ConstantValue;
303 assert(0 && "Unhandled case!");
307 assert(0 && "Unhandled case!");
311 // getVal - This function is identical to getValNonImprovising, except that if a
312 // value is not already defined, it "improvises" by creating a placeholder var
313 // that looks and acts just like the requested variable. When the value is
314 // defined later, all uses of the placeholder variable are replaced with the
317 static Value *getVal(const Type *Ty, const ValID &ID) {
318 if (Ty == Type::LabelTy)
319 ThrowException("Cannot use a basic block here");
321 // See if the value has already been defined.
322 Value *V = getValNonImprovising(Ty, ID);
325 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
326 ThrowException("Invalid use of a composite type!");
328 // If we reached here, we referenced either a symbol that we don't know about
329 // or an id number that hasn't been read yet. We may be referencing something
330 // forward, so just create an entry to be resolved later and get to it...
332 V = new Argument(Ty);
334 // Remember where this forward reference came from. FIXME, shouldn't we try
335 // to recycle these things??
336 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
339 if (inFunctionScope())
340 InsertValue(V, CurFun.LateResolveValues);
342 InsertValue(V, CurModule.LateResolveValues);
346 /// getBBVal - This is used for two purposes:
347 /// * If isDefinition is true, a new basic block with the specified ID is being
349 /// * If isDefinition is true, this is a reference to a basic block, which may
350 /// or may not be a forward reference.
352 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
353 assert(inFunctionScope() && "Can't get basic block at global scope!");
358 default: ThrowException("Illegal label reference " + ID.getName());
359 case ValID::NumberVal: // Is it a numbered definition?
360 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
361 CurFun.NumberedBlocks.resize(ID.Num+1);
362 BB = CurFun.NumberedBlocks[ID.Num];
364 case ValID::NameVal: // Is it a named definition?
366 if (Value *N = CurFun.CurrentFunction->
367 getSymbolTable().lookup(Type::LabelTy, Name))
368 BB = cast<BasicBlock>(N);
372 // See if the block has already been defined.
374 // If this is the definition of the block, make sure the existing value was
375 // just a forward reference. If it was a forward reference, there will be
376 // an entry for it in the PlaceHolderInfo map.
377 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
378 // The existing value was a definition, not a forward reference.
379 ThrowException("Redefinition of label " + ID.getName());
381 ID.destroy(); // Free strdup'd memory.
385 // Otherwise this block has not been seen before.
386 BB = new BasicBlock("", CurFun.CurrentFunction);
387 if (ID.Type == ValID::NameVal) {
388 BB->setName(ID.Name);
390 CurFun.NumberedBlocks[ID.Num] = BB;
393 // If this is not a definition, keep track of it so we can use it as a forward
396 // Remember where this forward reference came from.
397 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
399 // The forward declaration could have been inserted anywhere in the
400 // function: insert it into the correct place now.
401 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
402 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
409 //===----------------------------------------------------------------------===//
410 // Code to handle forward references in instructions
411 //===----------------------------------------------------------------------===//
413 // This code handles the late binding needed with statements that reference
414 // values not defined yet... for example, a forward branch, or the PHI node for
417 // This keeps a table (CurFun.LateResolveValues) of all such forward references
418 // and back patchs after we are done.
421 // ResolveDefinitions - If we could not resolve some defs at parsing
422 // time (forward branches, phi functions for loops, etc...) resolve the
425 static void ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
426 std::map<const Type*,ValueList> *FutureLateResolvers) {
427 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
428 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
429 E = LateResolvers.end(); LRI != E; ++LRI) {
430 ValueList &List = LRI->second;
431 while (!List.empty()) {
432 Value *V = List.back();
435 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
436 CurModule.PlaceHolderInfo.find(V);
437 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
439 ValID &DID = PHI->second.first;
441 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
443 V->replaceAllUsesWith(TheRealValue);
445 CurModule.PlaceHolderInfo.erase(PHI);
446 } else if (FutureLateResolvers) {
447 // Functions have their unresolved items forwarded to the module late
449 InsertValue(V, *FutureLateResolvers);
451 if (DID.Type == ValID::NameVal)
452 ThrowException("Reference to an invalid definition: '" +DID.getName()+
453 "' of type '" + V->getType()->getDescription() + "'",
456 ThrowException("Reference to an invalid definition: #" +
457 itostr(DID.Num) + " of type '" +
458 V->getType()->getDescription() + "'",
464 LateResolvers.clear();
467 // ResolveTypeTo - A brand new type was just declared. This means that (if
468 // name is not null) things referencing Name can be resolved. Otherwise, things
469 // refering to the number can be resolved. Do this now.
471 static void ResolveTypeTo(char *Name, const Type *ToTy) {
473 if (Name) D = ValID::create(Name);
474 else D = ValID::create((int)CurModule.Types.size());
476 std::map<ValID, PATypeHolder>::iterator I =
477 CurModule.LateResolveTypes.find(D);
478 if (I != CurModule.LateResolveTypes.end()) {
479 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
480 CurModule.LateResolveTypes.erase(I);
484 // setValueName - Set the specified value to the name given. The name may be
485 // null potentially, in which case this is a noop. The string passed in is
486 // assumed to be a malloc'd string buffer, and is free'd by this function.
488 static void setValueName(Value *V, char *NameStr) {
490 std::string Name(NameStr); // Copy string
491 free(NameStr); // Free old string
493 if (V->getType() == Type::VoidTy)
494 ThrowException("Can't assign name '" + Name+"' to value with void type!");
496 assert(inFunctionScope() && "Must be in function scope!");
497 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
498 if (ST.lookup(V->getType(), Name))
499 ThrowException("Redefinition of value named '" + Name + "' in the '" +
500 V->getType()->getDescription() + "' type plane!");
507 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
508 /// this is a declaration, otherwise it is a definition.
509 static void ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
510 bool isConstantGlobal, const Type *Ty,
511 Constant *Initializer) {
512 if (isa<FunctionType>(Ty))
513 ThrowException("Cannot declare global vars of function type!");
515 const PointerType *PTy = PointerType::get(Ty);
519 Name = NameStr; // Copy string
520 free(NameStr); // Free old string
523 // See if this global value was forward referenced. If so, recycle the
527 ID = ValID::create((char*)Name.c_str());
529 ID = ValID::create((int)CurModule.Values[PTy].size());
532 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
533 // Move the global to the end of the list, from whereever it was
534 // previously inserted.
535 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
536 CurModule.CurrentModule->getGlobalList().remove(GV);
537 CurModule.CurrentModule->getGlobalList().push_back(GV);
538 GV->setInitializer(Initializer);
539 GV->setLinkage(Linkage);
540 GV->setConstant(isConstantGlobal);
541 InsertValue(GV, CurModule.Values);
545 // If this global has a name, check to see if there is already a definition
546 // of this global in the module. If so, merge as appropriate. Note that
547 // this is really just a hack around problems in the CFE. :(
549 // We are a simple redefinition of a value, check to see if it is defined
550 // the same as the old one.
551 if (GlobalVariable *EGV =
552 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
553 // We are allowed to redefine a global variable in two circumstances:
554 // 1. If at least one of the globals is uninitialized or
555 // 2. If both initializers have the same value.
557 if (!EGV->hasInitializer() || !Initializer ||
558 EGV->getInitializer() == Initializer) {
560 // Make sure the existing global version gets the initializer! Make
561 // sure that it also gets marked const if the new version is.
562 if (Initializer && !EGV->hasInitializer())
563 EGV->setInitializer(Initializer);
564 if (isConstantGlobal)
565 EGV->setConstant(true);
566 EGV->setLinkage(Linkage);
570 ThrowException("Redefinition of global variable named '" + Name +
571 "' in the '" + Ty->getDescription() + "' type plane!");
575 // Otherwise there is no existing GV to use, create one now.
577 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
578 CurModule.CurrentModule);
579 InsertValue(GV, CurModule.Values);
582 // setTypeName - Set the specified type to the name given. The name may be
583 // null potentially, in which case this is a noop. The string passed in is
584 // assumed to be a malloc'd string buffer, and is freed by this function.
586 // This function returns true if the type has already been defined, but is
587 // allowed to be redefined in the specified context. If the name is a new name
588 // for the type plane, it is inserted and false is returned.
589 static bool setTypeName(const Type *T, char *NameStr) {
590 assert(!inFunctionScope() && "Can't give types function-local names!");
591 if (NameStr == 0) return false;
593 std::string Name(NameStr); // Copy string
594 free(NameStr); // Free old string
596 // We don't allow assigning names to void type
597 if (T == Type::VoidTy)
598 ThrowException("Can't assign name '" + Name + "' to the void type!");
600 // Set the type name, checking for conflicts as we do so.
601 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
603 if (AlreadyExists) { // Inserting a name that is already defined???
604 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
605 assert(Existing && "Conflict but no matching type?");
607 // There is only one case where this is allowed: when we are refining an
608 // opaque type. In this case, Existing will be an opaque type.
609 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
610 // We ARE replacing an opaque type!
611 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
615 // Otherwise, this is an attempt to redefine a type. That's okay if
616 // the redefinition is identical to the original. This will be so if
617 // Existing and T point to the same Type object. In this one case we
618 // allow the equivalent redefinition.
619 if (Existing == T) return true; // Yes, it's equal.
621 // Any other kind of (non-equivalent) redefinition is an error.
622 ThrowException("Redefinition of type named '" + Name + "' in the '" +
623 T->getDescription() + "' type plane!");
629 //===----------------------------------------------------------------------===//
630 // Code for handling upreferences in type names...
633 // TypeContains - Returns true if Ty directly contains E in it.
635 static bool TypeContains(const Type *Ty, const Type *E) {
636 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
637 E) != Ty->subtype_end();
642 // NestingLevel - The number of nesting levels that need to be popped before
643 // this type is resolved.
644 unsigned NestingLevel;
646 // LastContainedTy - This is the type at the current binding level for the
647 // type. Every time we reduce the nesting level, this gets updated.
648 const Type *LastContainedTy;
650 // UpRefTy - This is the actual opaque type that the upreference is
654 UpRefRecord(unsigned NL, OpaqueType *URTy)
655 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
659 // UpRefs - A list of the outstanding upreferences that need to be resolved.
660 static std::vector<UpRefRecord> UpRefs;
662 /// HandleUpRefs - Every time we finish a new layer of types, this function is
663 /// called. It loops through the UpRefs vector, which is a list of the
664 /// currently active types. For each type, if the up reference is contained in
665 /// the newly completed type, we decrement the level count. When the level
666 /// count reaches zero, the upreferenced type is the type that is passed in:
667 /// thus we can complete the cycle.
669 static PATypeHolder HandleUpRefs(const Type *ty) {
670 if (!ty->isAbstract()) return ty;
672 UR_OUT("Type '" << Ty->getDescription() <<
673 "' newly formed. Resolving upreferences.\n" <<
674 UpRefs.size() << " upreferences active!\n");
676 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
677 // to zero), we resolve them all together before we resolve them to Ty. At
678 // the end of the loop, if there is anything to resolve to Ty, it will be in
680 OpaqueType *TypeToResolve = 0;
682 for (unsigned i = 0; i != UpRefs.size(); ++i) {
683 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
684 << UpRefs[i].second->getDescription() << ") = "
685 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
686 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
687 // Decrement level of upreference
688 unsigned Level = --UpRefs[i].NestingLevel;
689 UpRefs[i].LastContainedTy = Ty;
690 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
691 if (Level == 0) { // Upreference should be resolved!
692 if (!TypeToResolve) {
693 TypeToResolve = UpRefs[i].UpRefTy;
695 UR_OUT(" * Resolving upreference for "
696 << UpRefs[i].second->getDescription() << "\n";
697 std::string OldName = UpRefs[i].UpRefTy->getDescription());
698 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
699 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
700 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
702 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
703 --i; // Do not skip the next element...
709 UR_OUT(" * Resolving upreference for "
710 << UpRefs[i].second->getDescription() << "\n";
711 std::string OldName = TypeToResolve->getDescription());
712 TypeToResolve->refineAbstractTypeTo(Ty);
719 //===----------------------------------------------------------------------===//
720 // RunVMAsmParser - Define an interface to this parser
721 //===----------------------------------------------------------------------===//
723 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
725 CurFilename = Filename;
726 llvmAsmlineno = 1; // Reset the current line number...
728 // Allocate a new module to read
729 CurModule.CurrentModule = new Module(Filename);
731 yyparse(); // Parse the file, potentially throwing exception
733 Module *Result = ParserResult;
735 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
744 llvm::Module *ModuleVal;
745 llvm::Function *FunctionVal;
746 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
747 llvm::BasicBlock *BasicBlockVal;
748 llvm::TerminatorInst *TermInstVal;
749 llvm::Instruction *InstVal;
750 llvm::Constant *ConstVal;
752 const llvm::Type *PrimType;
753 llvm::PATypeHolder *TypeVal;
754 llvm::Value *ValueVal;
756 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
757 std::vector<llvm::Value*> *ValueList;
758 std::list<llvm::PATypeHolder> *TypeList;
759 std::list<std::pair<llvm::Value*,
760 llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
761 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
762 std::vector<llvm::Constant*> *ConstVector;
764 llvm::GlobalValue::LinkageTypes Linkage;
772 char *StrVal; // This memory is strdup'd!
773 llvm::ValID ValIDVal; // strdup'd memory maybe!
775 llvm::Instruction::BinaryOps BinaryOpVal;
776 llvm::Instruction::TermOps TermOpVal;
777 llvm::Instruction::MemoryOps MemOpVal;
778 llvm::Instruction::OtherOps OtherOpVal;
779 llvm::Module::Endianness Endianness;
782 %type <ModuleVal> Module FunctionList
783 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
784 %type <BasicBlockVal> BasicBlock InstructionList
785 %type <TermInstVal> BBTerminatorInst
786 %type <InstVal> Inst InstVal MemoryInst
787 %type <ConstVal> ConstVal ConstExpr
788 %type <ConstVector> ConstVector
789 %type <ArgList> ArgList ArgListH
790 %type <ArgVal> ArgVal
791 %type <PHIList> PHIList
792 %type <ValueList> ValueRefList ValueRefListE // For call param lists
793 %type <ValueList> IndexList // For GEP derived indices
794 %type <TypeList> TypeListI ArgTypeListI
795 %type <JumpTable> JumpTable
796 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
797 %type <BoolVal> OptVolatile // 'volatile' or not
798 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
799 %type <Linkage> OptLinkage
800 %type <Endianness> BigOrLittle
802 // ValueRef - Unresolved reference to a definition or BB
803 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
804 %type <ValueVal> ResolvedVal // <type> <valref> pair
805 // Tokens and types for handling constant integer values
807 // ESINT64VAL - A negative number within long long range
808 %token <SInt64Val> ESINT64VAL
810 // EUINT64VAL - A positive number within uns. long long range
811 %token <UInt64Val> EUINT64VAL
812 %type <SInt64Val> EINT64VAL
814 %token <SIntVal> SINTVAL // Signed 32 bit ints...
815 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
816 %type <SIntVal> INTVAL
817 %token <FPVal> FPVAL // Float or Double constant
820 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
821 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
822 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
823 %token <PrimType> FLOAT DOUBLE TYPE LABEL
825 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
826 %type <StrVal> Name OptName OptAssign
829 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
830 %token DECLARE GLOBAL CONSTANT VOLATILE
831 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
832 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG
833 %token DEPLIBS CALL TAIL
835 // Basic Block Terminating Operators
836 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
839 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
840 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
841 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
843 // Memory Instructions
844 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
847 %type <OtherOpVal> ShiftOps
848 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG VANEXT
854 // Handle constant integer size restriction and conversion...
858 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
859 ThrowException("Value too large for type!");
864 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
865 EINT64VAL : EUINT64VAL {
866 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
867 ThrowException("Value too large for type!");
871 // Operations that are notably excluded from this list include:
872 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
874 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
875 LogicalOps : AND | OR | XOR;
876 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
878 ShiftOps : SHL | SHR;
883 // These are some types that allow classification if we only want a particular
884 // thing... for example, only a signed, unsigned, or integral type.
885 SIntType : LONG | INT | SHORT | SBYTE;
886 UIntType : ULONG | UINT | USHORT | UBYTE;
887 IntType : SIntType | UIntType;
888 FPType : FLOAT | DOUBLE;
890 // OptAssign - Value producing statements have an optional assignment component
891 OptAssign : Name '=' {
898 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
899 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
900 WEAK { $$ = GlobalValue::WeakLinkage; } |
901 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
902 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
904 //===----------------------------------------------------------------------===//
905 // Types includes all predefined types... except void, because it can only be
906 // used in specific contexts (function returning void for example). To have
907 // access to it, a user must explicitly use TypesV.
910 // TypesV includes all of 'Types', but it also includes the void type.
911 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
912 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
916 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
921 // Derived types are added later...
923 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
924 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
926 $$ = new PATypeHolder(OpaqueType::get());
929 $$ = new PATypeHolder($1);
931 UpRTypes : SymbolicValueRef { // Named types are also simple types...
932 $$ = new PATypeHolder(getTypeVal($1));
935 // Include derived types in the Types production.
937 UpRTypes : '\\' EUINT64VAL { // Type UpReference
938 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
939 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
940 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
941 $$ = new PATypeHolder(OT);
942 UR_OUT("New Upreference!\n");
944 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
945 std::vector<const Type*> Params;
946 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
947 E = $3->end(); I != E; ++I)
948 Params.push_back(*I);
949 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
950 if (isVarArg) Params.pop_back();
952 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
953 delete $3; // Delete the argument list
954 delete $1; // Delete the return type handle
956 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
957 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
960 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
961 const llvm::Type* ElemTy = $4->get();
962 if ((unsigned)$2 != $2) {
963 ThrowException("Unsigned result not equal to signed result");
965 if(!ElemTy->isPrimitiveType()) {
966 ThrowException("Elemental type of a PackedType must be primitive");
968 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
971 | '{' TypeListI '}' { // Structure type?
972 std::vector<const Type*> Elements;
973 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
974 E = $2->end(); I != E; ++I)
975 Elements.push_back(*I);
977 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
980 | '{' '}' { // Empty structure type?
981 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
983 | UpRTypes '*' { // Pointer type?
984 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
988 // TypeList - Used for struct declarations and as a basis for function type
989 // declaration type lists
991 TypeListI : UpRTypes {
992 $$ = new std::list<PATypeHolder>();
993 $$->push_back(*$1); delete $1;
995 | TypeListI ',' UpRTypes {
996 ($$=$1)->push_back(*$3); delete $3;
999 // ArgTypeList - List of types for a function type declaration...
1000 ArgTypeListI : TypeListI
1001 | TypeListI ',' DOTDOTDOT {
1002 ($$=$1)->push_back(Type::VoidTy);
1005 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1008 $$ = new std::list<PATypeHolder>();
1011 // ConstVal - The various declarations that go into the constant pool. This
1012 // production is used ONLY to represent constants that show up AFTER a 'const',
1013 // 'constant' or 'global' token at global scope. Constants that can be inlined
1014 // into other expressions (such as integers and constexprs) are handled by the
1015 // ResolvedVal, ValueRef and ConstValueRef productions.
1017 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1018 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1020 ThrowException("Cannot make array constant with type: '" +
1021 (*$1)->getDescription() + "'!");
1022 const Type *ETy = ATy->getElementType();
1023 int NumElements = ATy->getNumElements();
1025 // Verify that we have the correct size...
1026 if (NumElements != -1 && NumElements != (int)$3->size())
1027 ThrowException("Type mismatch: constant sized array initialized with " +
1028 utostr($3->size()) + " arguments, but has size of " +
1029 itostr(NumElements) + "!");
1031 // Verify all elements are correct type!
1032 for (unsigned i = 0; i < $3->size(); i++) {
1033 if (ETy != (*$3)[i]->getType())
1034 ThrowException("Element #" + utostr(i) + " is not of type '" +
1035 ETy->getDescription() +"' as required!\nIt is of type '"+
1036 (*$3)[i]->getType()->getDescription() + "'.");
1039 $$ = ConstantArray::get(ATy, *$3);
1040 delete $1; delete $3;
1043 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1045 ThrowException("Cannot make array constant with type: '" +
1046 (*$1)->getDescription() + "'!");
1048 int NumElements = ATy->getNumElements();
1049 if (NumElements != -1 && NumElements != 0)
1050 ThrowException("Type mismatch: constant sized array initialized with 0"
1051 " arguments, but has size of " + itostr(NumElements) +"!");
1052 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1055 | Types 'c' STRINGCONSTANT {
1056 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1058 ThrowException("Cannot make array constant with type: '" +
1059 (*$1)->getDescription() + "'!");
1061 int NumElements = ATy->getNumElements();
1062 const Type *ETy = ATy->getElementType();
1063 char *EndStr = UnEscapeLexed($3, true);
1064 if (NumElements != -1 && NumElements != (EndStr-$3))
1065 ThrowException("Can't build string constant of size " +
1066 itostr((int)(EndStr-$3)) +
1067 " when array has size " + itostr(NumElements) + "!");
1068 std::vector<Constant*> Vals;
1069 if (ETy == Type::SByteTy) {
1070 for (char *C = $3; C != EndStr; ++C)
1071 Vals.push_back(ConstantSInt::get(ETy, *C));
1072 } else if (ETy == Type::UByteTy) {
1073 for (char *C = $3; C != EndStr; ++C)
1074 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1077 ThrowException("Cannot build string arrays of non byte sized elements!");
1080 $$ = ConstantArray::get(ATy, Vals);
1083 | Types '<' ConstVector '>' { // Nonempty unsized arr
1084 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1086 ThrowException("Cannot make packed constant with type: '" +
1087 (*$1)->getDescription() + "'!");
1088 const Type *ETy = PTy->getElementType();
1089 int NumElements = PTy->getNumElements();
1091 // Verify that we have the correct size...
1092 if (NumElements != -1 && NumElements != (int)$3->size())
1093 ThrowException("Type mismatch: constant sized packed initialized with " +
1094 utostr($3->size()) + " arguments, but has size of " +
1095 itostr(NumElements) + "!");
1097 // Verify all elements are correct type!
1098 for (unsigned i = 0; i < $3->size(); i++) {
1099 if (ETy != (*$3)[i]->getType())
1100 ThrowException("Element #" + utostr(i) + " is not of type '" +
1101 ETy->getDescription() +"' as required!\nIt is of type '"+
1102 (*$3)[i]->getType()->getDescription() + "'.");
1105 $$ = ConstantPacked::get(PTy, *$3);
1106 delete $1; delete $3;
1108 | Types '{' ConstVector '}' {
1109 const StructType *STy = dyn_cast<StructType>($1->get());
1111 ThrowException("Cannot make struct constant with type: '" +
1112 (*$1)->getDescription() + "'!");
1114 if ($3->size() != STy->getNumContainedTypes())
1115 ThrowException("Illegal number of initializers for structure type!");
1117 // Check to ensure that constants are compatible with the type initializer!
1118 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1119 if ((*$3)[i]->getType() != STy->getElementType(i))
1120 ThrowException("Expected type '" +
1121 STy->getElementType(i)->getDescription() +
1122 "' for element #" + utostr(i) +
1123 " of structure initializer!");
1125 $$ = ConstantStruct::get(STy, *$3);
1126 delete $1; delete $3;
1129 const StructType *STy = dyn_cast<StructType>($1->get());
1131 ThrowException("Cannot make struct constant with type: '" +
1132 (*$1)->getDescription() + "'!");
1134 if (STy->getNumContainedTypes() != 0)
1135 ThrowException("Illegal number of initializers for structure type!");
1137 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1141 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1143 ThrowException("Cannot make null pointer constant with type: '" +
1144 (*$1)->getDescription() + "'!");
1146 $$ = ConstantPointerNull::get(PTy);
1150 $$ = UndefValue::get($1->get());
1153 | Types SymbolicValueRef {
1154 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1156 ThrowException("Global const reference must be a pointer type!");
1158 // ConstExprs can exist in the body of a function, thus creating
1159 // GlobalValues whenever they refer to a variable. Because we are in
1160 // the context of a function, getValNonImprovising will search the functions
1161 // symbol table instead of the module symbol table for the global symbol,
1162 // which throws things all off. To get around this, we just tell
1163 // getValNonImprovising that we are at global scope here.
1165 Function *SavedCurFn = CurFun.CurrentFunction;
1166 CurFun.CurrentFunction = 0;
1168 Value *V = getValNonImprovising(Ty, $2);
1170 CurFun.CurrentFunction = SavedCurFn;
1172 // If this is an initializer for a constant pointer, which is referencing a
1173 // (currently) undefined variable, create a stub now that shall be replaced
1174 // in the future with the right type of variable.
1177 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1178 const PointerType *PT = cast<PointerType>(Ty);
1180 // First check to see if the forward references value is already created!
1181 PerModuleInfo::GlobalRefsType::iterator I =
1182 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1184 if (I != CurModule.GlobalRefs.end()) {
1185 V = I->second; // Placeholder already exists, use it...
1189 if ($2.Type == ValID::NameVal) Name = $2.Name;
1191 // Create the forward referenced global.
1193 if (const FunctionType *FTy =
1194 dyn_cast<FunctionType>(PT->getElementType())) {
1195 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1196 CurModule.CurrentModule);
1198 GV = new GlobalVariable(PT->getElementType(), false,
1199 GlobalValue::ExternalLinkage, 0,
1200 Name, CurModule.CurrentModule);
1203 // Keep track of the fact that we have a forward ref to recycle it
1204 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1209 $$ = cast<GlobalValue>(V);
1210 delete $1; // Free the type handle
1213 if ($1->get() != $2->getType())
1214 ThrowException("Mismatched types for constant expression!");
1218 | Types ZEROINITIALIZER {
1219 const Type *Ty = $1->get();
1220 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1221 ThrowException("Cannot create a null initialized value of this type!");
1222 $$ = Constant::getNullValue(Ty);
1226 ConstVal : SIntType EINT64VAL { // integral constants
1227 if (!ConstantSInt::isValueValidForType($1, $2))
1228 ThrowException("Constant value doesn't fit in type!");
1229 $$ = ConstantSInt::get($1, $2);
1231 | UIntType EUINT64VAL { // integral constants
1232 if (!ConstantUInt::isValueValidForType($1, $2))
1233 ThrowException("Constant value doesn't fit in type!");
1234 $$ = ConstantUInt::get($1, $2);
1236 | BOOL TRUETOK { // Boolean constants
1237 $$ = ConstantBool::True;
1239 | BOOL FALSETOK { // Boolean constants
1240 $$ = ConstantBool::False;
1242 | FPType FPVAL { // Float & Double constants
1243 if (!ConstantFP::isValueValidForType($1, $2))
1244 ThrowException("Floating point constant invalid for type!!");
1245 $$ = ConstantFP::get($1, $2);
1249 ConstExpr: CAST '(' ConstVal TO Types ')' {
1250 if (!$3->getType()->isFirstClassType())
1251 ThrowException("cast constant expression from a non-primitive type: '" +
1252 $3->getType()->getDescription() + "'!");
1253 if (!$5->get()->isFirstClassType())
1254 ThrowException("cast constant expression to a non-primitive type: '" +
1255 $5->get()->getDescription() + "'!");
1256 $$ = ConstantExpr::getCast($3, $5->get());
1259 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1260 if (!isa<PointerType>($3->getType()))
1261 ThrowException("GetElementPtr requires a pointer operand!");
1263 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1264 // indices to uint struct indices for compatibility.
1265 generic_gep_type_iterator<std::vector<Value*>::iterator>
1266 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1267 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1268 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1269 if (isa<StructType>(*GTI)) // Only change struct indices
1270 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1271 if (CUI->getType() == Type::UByteTy)
1272 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1275 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1277 ThrowException("Index list invalid for constant getelementptr!");
1279 std::vector<Constant*> IdxVec;
1280 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1281 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1282 IdxVec.push_back(C);
1284 ThrowException("Indices to constant getelementptr must be constants!");
1288 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1290 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1291 if ($3->getType() != Type::BoolTy)
1292 ThrowException("Select condition must be of boolean type!");
1293 if ($5->getType() != $7->getType())
1294 ThrowException("Select operand types must match!");
1295 $$ = ConstantExpr::getSelect($3, $5, $7);
1297 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1298 if ($3->getType() != $5->getType())
1299 ThrowException("Binary operator types must match!");
1300 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1301 // To retain backward compatibility with these early compilers, we emit a
1302 // cast to the appropriate integer type automatically if we are in the
1303 // broken case. See PR424 for more information.
1304 if (!isa<PointerType>($3->getType())) {
1305 $$ = ConstantExpr::get($1, $3, $5);
1307 const Type *IntPtrTy = 0;
1308 switch (CurModule.CurrentModule->getPointerSize()) {
1309 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1310 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1311 default: ThrowException("invalid pointer binary constant expr!");
1313 $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1314 ConstantExpr::getCast($5, IntPtrTy));
1315 $$ = ConstantExpr::getCast($$, $3->getType());
1318 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1319 if ($3->getType() != $5->getType())
1320 ThrowException("Logical operator types must match!");
1321 if (!$3->getType()->isIntegral())
1322 ThrowException("Logical operands must have integral types!");
1323 $$ = ConstantExpr::get($1, $3, $5);
1325 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1326 if ($3->getType() != $5->getType())
1327 ThrowException("setcc operand types must match!");
1328 $$ = ConstantExpr::get($1, $3, $5);
1330 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1331 if ($5->getType() != Type::UByteTy)
1332 ThrowException("Shift count for shift constant must be unsigned byte!");
1333 if (!$3->getType()->isInteger())
1334 ThrowException("Shift constant expression requires integer operand!");
1335 $$ = ConstantExpr::get($1, $3, $5);
1339 // ConstVector - A list of comma separated constants.
1340 ConstVector : ConstVector ',' ConstVal {
1341 ($$ = $1)->push_back($3);
1344 $$ = new std::vector<Constant*>();
1349 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1350 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1353 //===----------------------------------------------------------------------===//
1354 // Rules to match Modules
1355 //===----------------------------------------------------------------------===//
1357 // Module rule: Capture the result of parsing the whole file into a result
1360 Module : FunctionList {
1361 $$ = ParserResult = $1;
1362 CurModule.ModuleDone();
1365 // FunctionList - A list of functions, preceeded by a constant pool.
1367 FunctionList : FunctionList Function {
1369 CurFun.FunctionDone();
1371 | FunctionList FunctionProto {
1374 | FunctionList IMPLEMENTATION {
1378 $$ = CurModule.CurrentModule;
1379 // Emit an error if there are any unresolved types left.
1380 if (!CurModule.LateResolveTypes.empty()) {
1381 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1382 if (DID.Type == ValID::NameVal)
1383 ThrowException("Reference to an undefined type: '"+DID.getName() + "'");
1385 ThrowException("Reference to an undefined type: #" + itostr(DID.Num));
1389 // ConstPool - Constants with optional names assigned to them.
1390 ConstPool : ConstPool OptAssign TYPE TypesV {
1391 // Eagerly resolve types. This is not an optimization, this is a
1392 // requirement that is due to the fact that we could have this:
1394 // %list = type { %list * }
1395 // %list = type { %list * } ; repeated type decl
1397 // If types are not resolved eagerly, then the two types will not be
1398 // determined to be the same type!
1400 ResolveTypeTo($2, *$4);
1402 if (!setTypeName(*$4, $2) && !$2) {
1403 // If this is a named type that is not a redefinition, add it to the slot
1405 CurModule.Types.push_back(*$4);
1410 | ConstPool FunctionProto { // Function prototypes can be in const pool
1412 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1413 if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1414 ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1416 | ConstPool OptAssign EXTERNAL GlobalType Types {
1417 ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1420 | ConstPool TARGET TargetDefinition {
1422 | ConstPool DEPLIBS '=' LibrariesDefinition {
1424 | /* empty: end of list */ {
1429 BigOrLittle : BIG { $$ = Module::BigEndian; };
1430 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1432 TargetDefinition : ENDIAN '=' BigOrLittle {
1433 CurModule.CurrentModule->setEndianness($3);
1435 | POINTERSIZE '=' EUINT64VAL {
1437 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1439 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1441 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1443 | TRIPLE '=' STRINGCONSTANT {
1444 CurModule.CurrentModule->setTargetTriple($3);
1448 LibrariesDefinition : '[' LibList ']';
1450 LibList : LibList ',' STRINGCONSTANT {
1451 CurModule.CurrentModule->addLibrary($3);
1455 CurModule.CurrentModule->addLibrary($1);
1458 | /* empty: end of list */ {
1462 //===----------------------------------------------------------------------===//
1463 // Rules to match Function Headers
1464 //===----------------------------------------------------------------------===//
1466 Name : VAR_ID | STRINGCONSTANT;
1467 OptName : Name | /*empty*/ { $$ = 0; };
1469 ArgVal : Types OptName {
1470 if (*$1 == Type::VoidTy)
1471 ThrowException("void typed arguments are invalid!");
1472 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1475 ArgListH : ArgListH ',' ArgVal {
1481 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1486 ArgList : ArgListH {
1489 | ArgListH ',' DOTDOTDOT {
1491 $$->push_back(std::pair<PATypeHolder*,
1492 char*>(new PATypeHolder(Type::VoidTy), 0));
1495 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1496 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1502 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1504 std::string FunctionName($2);
1505 free($2); // Free strdup'd memory!
1507 if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1508 ThrowException("LLVM functions cannot return aggregate types!");
1510 std::vector<const Type*> ParamTypeList;
1511 if ($4) { // If there are arguments...
1512 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1513 I != $4->end(); ++I)
1514 ParamTypeList.push_back(I->first->get());
1517 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1518 if (isVarArg) ParamTypeList.pop_back();
1520 const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1521 const PointerType *PFT = PointerType::get(FT);
1525 if (!FunctionName.empty()) {
1526 ID = ValID::create((char*)FunctionName.c_str());
1528 ID = ValID::create((int)CurModule.Values[PFT].size());
1532 // See if this function was forward referenced. If so, recycle the object.
1533 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1534 // Move the function to the end of the list, from whereever it was
1535 // previously inserted.
1536 Fn = cast<Function>(FWRef);
1537 CurModule.CurrentModule->getFunctionList().remove(Fn);
1538 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1539 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1540 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1541 // If this is the case, either we need to be a forward decl, or it needs
1543 if (!CurFun.isDeclare && !Fn->isExternal())
1544 ThrowException("Redefinition of function '" + FunctionName + "'!");
1546 // Make sure to strip off any argument names so we can't get conflicts.
1547 if (Fn->isExternal())
1548 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1552 } else { // Not already defined?
1553 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1554 CurModule.CurrentModule);
1555 InsertValue(Fn, CurModule.Values);
1558 CurFun.FunctionStart(Fn);
1560 // Add all of the arguments we parsed to the function...
1561 if ($4) { // Is null if empty...
1562 if (isVarArg) { // Nuke the last entry
1563 assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1564 "Not a varargs marker!");
1565 delete $4->back().first;
1566 $4->pop_back(); // Delete the last entry
1568 Function::arg_iterator ArgIt = Fn->arg_begin();
1569 for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1570 I != $4->end(); ++I, ++ArgIt) {
1571 delete I->first; // Delete the typeholder...
1573 setValueName(ArgIt, I->second); // Insert arg into symtab...
1577 delete $4; // We're now done with the argument list
1581 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1583 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1584 $$ = CurFun.CurrentFunction;
1586 // Make sure that we keep track of the linkage type even if there was a
1587 // previous "declare".
1591 END : ENDTOK | '}'; // Allow end of '}' to end a function
1593 Function : BasicBlockList END {
1597 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1598 $$ = CurFun.CurrentFunction;
1599 CurFun.FunctionDone();
1602 //===----------------------------------------------------------------------===//
1603 // Rules to match Basic Blocks
1604 //===----------------------------------------------------------------------===//
1606 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1607 $$ = ValID::create($1);
1610 $$ = ValID::create($1);
1612 | FPVAL { // Perhaps it's an FP constant?
1613 $$ = ValID::create($1);
1616 $$ = ValID::create(ConstantBool::True);
1619 $$ = ValID::create(ConstantBool::False);
1622 $$ = ValID::createNull();
1625 $$ = ValID::createUndef();
1627 | '<' ConstVector '>' { // Nonempty unsized packed vector
1628 const Type *ETy = (*$2)[0]->getType();
1629 int NumElements = $2->size();
1631 PackedType* pt = PackedType::get(ETy, NumElements);
1632 PATypeHolder* PTy = new PATypeHolder(
1640 // Verify all elements are correct type!
1641 for (unsigned i = 0; i < $2->size(); i++) {
1642 if (ETy != (*$2)[i]->getType())
1643 ThrowException("Element #" + utostr(i) + " is not of type '" +
1644 ETy->getDescription() +"' as required!\nIt is of type '" +
1645 (*$2)[i]->getType()->getDescription() + "'.");
1648 $$ = ValID::create(ConstantPacked::get(pt, *$2));
1649 delete PTy; delete $2;
1652 $$ = ValID::create($1);
1655 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1658 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1659 $$ = ValID::create($1);
1661 | Name { // Is it a named reference...?
1662 $$ = ValID::create($1);
1665 // ValueRef - A reference to a definition... either constant or symbolic
1666 ValueRef : SymbolicValueRef | ConstValueRef;
1669 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1670 // type immediately preceeds the value reference, and allows complex constant
1671 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1672 ResolvedVal : Types ValueRef {
1673 $$ = getVal(*$1, $2); delete $1;
1676 BasicBlockList : BasicBlockList BasicBlock {
1679 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1684 // Basic blocks are terminated by branching instructions:
1685 // br, br/cc, switch, ret
1687 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1688 setValueName($3, $2);
1691 $1->getInstList().push_back($3);
1696 InstructionList : InstructionList Inst {
1697 $1->getInstList().push_back($2);
1701 $$ = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1703 // Make sure to move the basic block to the correct location in the
1704 // function, instead of leaving it inserted wherever it was first
1706 Function::BasicBlockListType &BBL =
1707 CurFun.CurrentFunction->getBasicBlockList();
1708 BBL.splice(BBL.end(), BBL, $$);
1711 $$ = getBBVal(ValID::create($1), true);
1713 // Make sure to move the basic block to the correct location in the
1714 // function, instead of leaving it inserted wherever it was first
1716 Function::BasicBlockListType &BBL =
1717 CurFun.CurrentFunction->getBasicBlockList();
1718 BBL.splice(BBL.end(), BBL, $$);
1721 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1722 $$ = new ReturnInst($2);
1724 | RET VOID { // Return with no result...
1725 $$ = new ReturnInst();
1727 | BR LABEL ValueRef { // Unconditional Branch...
1728 $$ = new BranchInst(getBBVal($3));
1729 } // Conditional Branch...
1730 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1731 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1733 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1734 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
1737 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1739 for (; I != E; ++I) {
1740 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
1741 S->addCase(CI, I->second);
1743 ThrowException("Switch case is constant, but not a simple integer!");
1747 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1748 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
1751 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO LABEL ValueRef
1752 UNWIND LABEL ValueRef {
1753 const PointerType *PFTy;
1754 const FunctionType *Ty;
1756 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1757 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1758 // Pull out the types of all of the arguments...
1759 std::vector<const Type*> ParamTypes;
1761 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1763 ParamTypes.push_back((*I)->getType());
1766 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1767 if (isVarArg) ParamTypes.pop_back();
1769 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1770 PFTy = PointerType::get(Ty);
1773 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1775 BasicBlock *Normal = getBBVal($9);
1776 BasicBlock *Except = getBBVal($12);
1778 // Create the call node...
1779 if (!$5) { // Has no arguments?
1780 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1781 } else { // Has arguments?
1782 // Loop through FunctionType's arguments and ensure they are specified
1785 FunctionType::param_iterator I = Ty->param_begin();
1786 FunctionType::param_iterator E = Ty->param_end();
1787 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1789 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1790 if ((*ArgI)->getType() != *I)
1791 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1792 (*I)->getDescription() + "'!");
1794 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1795 ThrowException("Invalid number of parameters detected!");
1797 $$ = new InvokeInst(V, Normal, Except, *$5);
1803 $$ = new UnwindInst();
1806 $$ = new UnreachableInst();
1811 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1813 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1815 ThrowException("May only switch on a constant pool value!");
1817 $$->push_back(std::make_pair(V, getBBVal($6)));
1819 | IntType ConstValueRef ',' LABEL ValueRef {
1820 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1821 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1824 ThrowException("May only switch on a constant pool value!");
1826 $$->push_back(std::make_pair(V, getBBVal($5)));
1829 Inst : OptAssign InstVal {
1830 // Is this definition named?? if so, assign the name...
1831 setValueName($2, $1);
1836 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1837 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1838 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
1841 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1843 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1848 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1849 $$ = new std::vector<Value*>();
1852 | ValueRefList ',' ResolvedVal {
1857 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1858 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1860 OptTailCall : TAIL CALL {
1869 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1870 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
1871 !isa<PackedType>((*$2).get()))
1873 "Arithmetic operator requires integer, FP, or packed operands!");
1874 if(isa<PackedType>((*$2).get()) && $1 == Instruction::Rem) {
1876 "Rem not supported on packed types!");
1878 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1880 ThrowException("binary operator returned null!");
1883 | LogicalOps Types ValueRef ',' ValueRef {
1884 if (!(*$2)->isIntegral())
1885 ThrowException("Logical operator requires integral operands!");
1886 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1888 ThrowException("binary operator returned null!");
1891 | SetCondOps Types ValueRef ',' ValueRef {
1892 if(isa<PackedType>((*$2).get())) {
1894 "PackedTypes currently not supported in setcc instructions!");
1896 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1898 ThrowException("binary operator returned null!");
1902 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1903 << " Replacing with 'xor'.\n";
1905 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1907 ThrowException("Expected integral type for not instruction!");
1909 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1911 ThrowException("Could not create a xor instruction!");
1913 | ShiftOps ResolvedVal ',' ResolvedVal {
1914 if ($4->getType() != Type::UByteTy)
1915 ThrowException("Shift amount must be ubyte!");
1916 if (!$2->getType()->isInteger())
1917 ThrowException("Shift constant expression requires integer operand!");
1918 $$ = new ShiftInst($1, $2, $4);
1920 | CAST ResolvedVal TO Types {
1921 if (!$4->get()->isFirstClassType())
1922 ThrowException("cast instruction to a non-primitive type: '" +
1923 $4->get()->getDescription() + "'!");
1924 $$ = new CastInst($2, *$4);
1927 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1928 if ($2->getType() != Type::BoolTy)
1929 ThrowException("select condition must be boolean!");
1930 if ($4->getType() != $6->getType())
1931 ThrowException("select value types should match!");
1932 $$ = new SelectInst($2, $4, $6);
1934 | VAARG ResolvedVal ',' Types {
1935 $$ = new VAArgInst($2, *$4);
1938 | VANEXT ResolvedVal ',' Types {
1939 $$ = new VANextInst($2, *$4);
1943 const Type *Ty = $2->front().first->getType();
1944 if (!Ty->isFirstClassType())
1945 ThrowException("PHI node operands must be of first class type!");
1946 $$ = new PHINode(Ty);
1947 ((PHINode*)$$)->reserveOperandSpace($2->size());
1948 while ($2->begin() != $2->end()) {
1949 if ($2->front().first->getType() != Ty)
1950 ThrowException("All elements of a PHI node must be of the same type!");
1951 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1954 delete $2; // Free the list...
1956 | OptTailCall TypesV ValueRef '(' ValueRefListE ')' {
1957 const PointerType *PFTy;
1958 const FunctionType *Ty;
1960 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1961 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1962 // Pull out the types of all of the arguments...
1963 std::vector<const Type*> ParamTypes;
1965 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1967 ParamTypes.push_back((*I)->getType());
1970 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1971 if (isVarArg) ParamTypes.pop_back();
1973 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1974 ThrowException("LLVM functions cannot return aggregate types!");
1976 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1977 PFTy = PointerType::get(Ty);
1980 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1982 // Create the call node...
1983 if (!$5) { // Has no arguments?
1984 // Make sure no arguments is a good thing!
1985 if (Ty->getNumParams() != 0)
1986 ThrowException("No arguments passed to a function that "
1987 "expects arguments!");
1989 $$ = new CallInst(V, std::vector<Value*>());
1990 } else { // Has arguments?
1991 // Loop through FunctionType's arguments and ensure they are specified
1994 FunctionType::param_iterator I = Ty->param_begin();
1995 FunctionType::param_iterator E = Ty->param_end();
1996 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1998 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1999 if ((*ArgI)->getType() != *I)
2000 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2001 (*I)->getDescription() + "'!");
2003 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2004 ThrowException("Invalid number of parameters detected!");
2006 $$ = new CallInst(V, *$5);
2008 cast<CallInst>($$)->setTailCall($1);
2017 // IndexList - List of indices for GEP based instructions...
2018 IndexList : ',' ValueRefList {
2021 $$ = new std::vector<Value*>();
2024 OptVolatile : VOLATILE {
2033 MemoryInst : MALLOC Types {
2034 $$ = new MallocInst(*$2);
2037 | MALLOC Types ',' UINT ValueRef {
2038 $$ = new MallocInst(*$2, getVal($4, $5));
2042 $$ = new AllocaInst(*$2);
2045 | ALLOCA Types ',' UINT ValueRef {
2046 $$ = new AllocaInst(*$2, getVal($4, $5));
2049 | FREE ResolvedVal {
2050 if (!isa<PointerType>($2->getType()))
2051 ThrowException("Trying to free nonpointer type " +
2052 $2->getType()->getDescription() + "!");
2053 $$ = new FreeInst($2);
2056 | OptVolatile LOAD Types ValueRef {
2057 if (!isa<PointerType>($3->get()))
2058 ThrowException("Can't load from nonpointer type: " +
2059 (*$3)->getDescription());
2060 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2061 ThrowException("Can't load from pointer of non-first-class type: " +
2062 (*$3)->getDescription());
2063 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2066 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2067 const PointerType *PT = dyn_cast<PointerType>($5->get());
2069 ThrowException("Can't store to a nonpointer type: " +
2070 (*$5)->getDescription());
2071 const Type *ElTy = PT->getElementType();
2072 if (ElTy != $3->getType())
2073 ThrowException("Can't store '" + $3->getType()->getDescription() +
2074 "' into space of type '" + ElTy->getDescription() + "'!");
2076 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2079 | GETELEMENTPTR Types ValueRef IndexList {
2080 if (!isa<PointerType>($2->get()))
2081 ThrowException("getelementptr insn requires pointer operand!");
2083 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2084 // indices to uint struct indices for compatibility.
2085 generic_gep_type_iterator<std::vector<Value*>::iterator>
2086 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2087 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2088 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2089 if (isa<StructType>(*GTI)) // Only change struct indices
2090 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2091 if (CUI->getType() == Type::UByteTy)
2092 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2094 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2095 ThrowException("Invalid getelementptr indices for type '" +
2096 (*$2)->getDescription()+ "'!");
2097 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2098 delete $2; delete $4;
2103 int yyerror(const char *ErrorMsg) {
2105 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2106 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2107 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2108 if (yychar == YYEMPTY || yychar == 0)
2109 errMsg += "end-of-file.";
2111 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2112 ThrowException(errMsg);