1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Module.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iOperators.h"
21 #include "llvm/iPHINode.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "Support/STLExtras.h"
29 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
30 int yylex(); // declaration" of xxx warnings.
35 static Module *ParserResult;
36 std::string CurFilename;
38 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
39 // relating to upreferences in the input stream.
41 //#define DEBUG_UPREFS 1
43 #define UR_OUT(X) std::cerr << X
48 #define YYERROR_VERBOSE 1
50 // HACK ALERT: This variable is used to implement the automatic conversion of
51 // variable argument instructions from their old to new forms. When this
52 // compatiblity "Feature" is removed, this should be too.
54 static BasicBlock *CurBB;
55 static bool ObsoleteVarArgs;
58 // This contains info used when building the body of a function. It is
59 // destroyed when the function is completed.
61 typedef std::vector<Value *> ValueList; // Numbered defs
62 static void ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
63 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
65 static struct PerModuleInfo {
66 Module *CurrentModule;
67 std::map<const Type *, ValueList> Values; // Module level numbered definitions
68 std::map<const Type *,ValueList> LateResolveValues;
69 std::vector<PATypeHolder> Types;
70 std::map<ValID, PATypeHolder> LateResolveTypes;
72 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
73 /// how they were referenced and one which line of the input they came from so
74 /// that we can resolve them later and print error messages as appropriate.
75 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
77 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
78 // references to global values. Global values may be referenced before they
79 // are defined, and if so, the temporary object that they represent is held
80 // here. This is used for forward references of ConstantPointerRefs.
82 typedef std::map<std::pair<const PointerType *,
83 ValID>, GlobalValue*> GlobalRefsType;
84 GlobalRefsType GlobalRefs;
87 // If we could not resolve some functions at function compilation time
88 // (calls to functions before they are defined), resolve them now... Types
89 // are resolved when the constant pool has been completely parsed.
91 ResolveDefinitions(LateResolveValues);
93 // Check to make sure that all global value forward references have been
96 if (!GlobalRefs.empty()) {
97 std::string UndefinedReferences = "Unresolved global references exist:\n";
99 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
101 UndefinedReferences += " " + I->first.first->getDescription() + " " +
102 I->first.second.getName() + "\n";
104 ThrowException(UndefinedReferences);
107 Values.clear(); // Clear out function local definitions
113 // DeclareNewGlobalValue - Called every time a new GV has been defined. This
114 // is used to remove things from the forward declaration map, resolving them
115 // to the correct thing as needed.
117 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
118 // Check to see if there is a forward reference to this global variable...
119 // if there is, eliminate it and patch the reference to use the new def'n.
120 GlobalRefsType::iterator I =
121 GlobalRefs.find(std::make_pair(GV->getType(), D));
123 if (I != GlobalRefs.end()) {
124 GlobalValue *OldGV = I->second; // Get the placeholder...
125 I->first.second.destroy(); // Free string memory if necessary
127 // Replace all uses of the placeholder with the new GV
128 OldGV->replaceAllUsesWith(GV);
130 // Remove OldGV from the module...
131 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(OldGV))
132 CurrentModule->getGlobalList().erase(GVar);
134 CurrentModule->getFunctionList().erase(cast<Function>(OldGV));
136 // Remove the map entry for the global now that it has been created...
143 static struct PerFunctionInfo {
144 Function *CurrentFunction; // Pointer to current function being created
146 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
147 std::map<const Type*, ValueList> LateResolveValues;
148 std::vector<PATypeHolder> Types;
149 std::map<ValID, PATypeHolder> LateResolveTypes;
150 bool isDeclare; // Is this function a forward declararation?
152 /// BBForwardRefs - When we see forward references to basic blocks, keep
153 /// track of them here.
154 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
155 std::vector<BasicBlock*> NumberedBlocks;
158 inline PerFunctionInfo() {
163 inline void FunctionStart(Function *M) {
168 void FunctionDone() {
169 NumberedBlocks.clear();
171 // Any forward referenced blocks left?
172 if (!BBForwardRefs.empty())
173 ThrowException("Undefined reference to label " +
174 BBForwardRefs.begin()->second.first.getName());
176 // Resolve all forward references now.
177 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
179 // Make sure to resolve any constant expr references that might exist within
180 // the function we just declared itself.
182 if (CurrentFunction->hasName()) {
183 FID = ValID::create((char*)CurrentFunction->getName().c_str());
185 // Figure out which slot number if is...
186 ValueList &List = CurModule.Values[CurrentFunction->getType()];
187 for (unsigned i = 0; ; ++i) {
188 assert(i < List.size() && "Function not found!");
189 if (List[i] == CurrentFunction) {
190 FID = ValID::create((int)i);
195 CurModule.DeclareNewGlobalValue(CurrentFunction, FID);
197 Values.clear(); // Clear out function local definitions
198 Types.clear(); // Clear out function local types
202 } CurFun; // Info for the current function...
204 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
207 //===----------------------------------------------------------------------===//
208 // Code to handle definitions of all the types
209 //===----------------------------------------------------------------------===//
211 static int InsertValue(Value *V,
212 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
213 if (V->hasName()) return -1; // Is this a numbered definition?
215 // Yes, insert the value into the value table...
216 ValueList &List = ValueTab[V->getType()];
218 return List.size()-1;
221 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
223 case ValID::NumberVal: { // Is it a numbered definition?
224 unsigned Num = (unsigned)D.Num;
226 // Module constants occupy the lowest numbered slots...
227 if (Num < CurModule.Types.size())
228 return CurModule.Types[Num];
230 Num -= CurModule.Types.size();
232 // Check that the number is within bounds...
233 if (Num <= CurFun.Types.size())
234 return CurFun.Types[Num];
237 case ValID::NameVal: { // Is it a named definition?
238 std::string Name(D.Name);
239 SymbolTable *SymTab = 0;
241 if (inFunctionScope()) {
242 SymTab = &CurFun.CurrentFunction->getSymbolTable();
243 N = SymTab->lookupType(Name);
247 // Symbol table doesn't automatically chain yet... because the function
248 // hasn't been added to the module...
250 SymTab = &CurModule.CurrentModule->getSymbolTable();
251 N = SymTab->lookupType(Name);
255 D.destroy(); // Free old strdup'd memory...
256 return cast<Type>(N);
259 ThrowException("Internal parser error: Invalid symbol type reference!");
262 // If we reached here, we referenced either a symbol that we don't know about
263 // or an id number that hasn't been read yet. We may be referencing something
264 // forward, so just create an entry to be resolved later and get to it...
266 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
268 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
269 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
271 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
272 if (I != LateResolver.end()) {
276 Type *Typ = OpaqueType::get();
277 LateResolver.insert(std::make_pair(D, Typ));
281 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
282 SymbolTable &SymTab =
283 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
284 CurModule.CurrentModule->getSymbolTable();
285 return SymTab.lookup(Ty, Name);
288 // getValNonImprovising - Look up the value specified by the provided type and
289 // the provided ValID. If the value exists and has already been defined, return
290 // it. Otherwise return null.
292 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
293 if (isa<FunctionType>(Ty))
294 ThrowException("Functions are not values and "
295 "must be referenced as pointers");
298 case ValID::NumberVal: { // Is it a numbered definition?
299 unsigned Num = (unsigned)D.Num;
301 // Module constants occupy the lowest numbered slots...
302 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
303 if (VI != CurModule.Values.end()) {
304 if (Num < VI->second.size())
305 return VI->second[Num];
306 Num -= VI->second.size();
309 // Make sure that our type is within bounds
310 VI = CurFun.Values.find(Ty);
311 if (VI == CurFun.Values.end()) return 0;
313 // Check that the number is within bounds...
314 if (VI->second.size() <= Num) return 0;
316 return VI->second[Num];
319 case ValID::NameVal: { // Is it a named definition?
320 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
321 if (N == 0) return 0;
323 D.destroy(); // Free old strdup'd memory...
327 // Check to make sure that "Ty" is an integral type, and that our
328 // value will fit into the specified type...
329 case ValID::ConstSIntVal: // Is it a constant pool reference??
330 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
331 ThrowException("Signed integral constant '" +
332 itostr(D.ConstPool64) + "' is invalid for type '" +
333 Ty->getDescription() + "'!");
334 return ConstantSInt::get(Ty, D.ConstPool64);
336 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
337 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
338 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
339 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
340 "' is invalid or out of range!");
341 } else { // This is really a signed reference. Transmogrify.
342 return ConstantSInt::get(Ty, D.ConstPool64);
345 return ConstantUInt::get(Ty, D.UConstPool64);
348 case ValID::ConstFPVal: // Is it a floating point const pool reference?
349 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
350 ThrowException("FP constant invalid for type!!");
351 return ConstantFP::get(Ty, D.ConstPoolFP);
353 case ValID::ConstNullVal: // Is it a null value?
354 if (!isa<PointerType>(Ty))
355 ThrowException("Cannot create a a non pointer null!");
356 return ConstantPointerNull::get(cast<PointerType>(Ty));
358 case ValID::ConstantVal: // Fully resolved constant?
359 if (D.ConstantValue->getType() != Ty)
360 ThrowException("Constant expression type different from required type!");
361 return D.ConstantValue;
364 assert(0 && "Unhandled case!");
368 assert(0 && "Unhandled case!");
372 // getVal - This function is identical to getValNonImprovising, except that if a
373 // value is not already defined, it "improvises" by creating a placeholder var
374 // that looks and acts just like the requested variable. When the value is
375 // defined later, all uses of the placeholder variable are replaced with the
378 static Value *getVal(const Type *Ty, const ValID &ID) {
379 if (Ty == Type::LabelTy)
380 ThrowException("Cannot use a basic block here");
382 // See if the value has already been defined.
383 Value *V = getValNonImprovising(Ty, ID);
386 // If we reached here, we referenced either a symbol that we don't know about
387 // or an id number that hasn't been read yet. We may be referencing something
388 // forward, so just create an entry to be resolved later and get to it...
390 V = new Argument(Ty);
392 // Remember where this forward reference came from. FIXME, shouldn't we try
393 // to recycle these things??
394 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
397 if (inFunctionScope())
398 InsertValue(V, CurFun.LateResolveValues);
400 InsertValue(V, CurModule.LateResolveValues);
404 /// getBBVal - This is used for two purposes:
405 /// * If isDefinition is true, a new basic block with the specified ID is being
407 /// * If isDefinition is true, this is a reference to a basic block, which may
408 /// or may not be a forward reference.
410 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
411 assert(inFunctionScope() && "Can't get basic block at global scope!");
416 default: ThrowException("Illegal label reference " + ID.getName());
417 case ValID::NumberVal: // Is it a numbered definition?
418 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
419 CurFun.NumberedBlocks.resize(ID.Num+1);
420 BB = CurFun.NumberedBlocks[ID.Num];
422 case ValID::NameVal: // Is it a named definition?
424 if (Value *N = lookupInSymbolTable(Type::LabelTy, Name))
425 BB = cast<BasicBlock>(N);
429 // See if the block has already been defined.
431 // If this is the definition of the block, make sure the existing value was
432 // just a forward reference. If it was a forward reference, there will be
433 // an entry for it in the PlaceHolderInfo map.
434 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
435 // The existing value was a definition, not a forward reference.
436 ThrowException("Redefinition of label " + ID.getName());
438 ID.destroy(); // Free strdup'd memory.
442 // Otherwise this block has not been seen before.
443 BB = new BasicBlock("", CurFun.CurrentFunction);
444 if (ID.Type == ValID::NameVal) {
445 BB->setName(ID.Name);
447 CurFun.NumberedBlocks[ID.Num] = BB;
450 // If this is not a definition, keep track of it so we can use it as a forward
453 // Remember where this forward reference came from.
454 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
456 // The forward declaration could have been inserted anywhere in the
457 // function: insert it into the correct place now.
458 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
459 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
466 //===----------------------------------------------------------------------===//
467 // Code to handle forward references in instructions
468 //===----------------------------------------------------------------------===//
470 // This code handles the late binding needed with statements that reference
471 // values not defined yet... for example, a forward branch, or the PHI node for
474 // This keeps a table (CurFun.LateResolveValues) of all such forward references
475 // and back patchs after we are done.
478 // ResolveDefinitions - If we could not resolve some defs at parsing
479 // time (forward branches, phi functions for loops, etc...) resolve the
482 static void ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
483 std::map<const Type*,ValueList> *FutureLateResolvers) {
484 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
485 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
486 E = LateResolvers.end(); LRI != E; ++LRI) {
487 ValueList &List = LRI->second;
488 while (!List.empty()) {
489 Value *V = List.back();
492 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
493 CurModule.PlaceHolderInfo.find(V);
494 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
496 ValID &DID = PHI->second.first;
498 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
500 V->replaceAllUsesWith(TheRealValue);
502 CurModule.PlaceHolderInfo.erase(PHI);
503 } else if (FutureLateResolvers) {
504 // Functions have their unresolved items forwarded to the module late
506 InsertValue(V, *FutureLateResolvers);
508 if (DID.Type == ValID::NameVal)
509 ThrowException("Reference to an invalid definition: '" +DID.getName()+
510 "' of type '" + V->getType()->getDescription() + "'",
513 ThrowException("Reference to an invalid definition: #" +
514 itostr(DID.Num) + " of type '" +
515 V->getType()->getDescription() + "'",
521 LateResolvers.clear();
524 // ResolveTypeTo - A brand new type was just declared. This means that (if
525 // name is not null) things referencing Name can be resolved. Otherwise, things
526 // refering to the number can be resolved. Do this now.
528 static void ResolveTypeTo(char *Name, const Type *ToTy) {
529 std::vector<PATypeHolder> &Types = inFunctionScope() ?
530 CurFun.Types : CurModule.Types;
533 if (Name) D = ValID::create(Name);
534 else D = ValID::create((int)Types.size());
536 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
537 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
539 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
540 if (I != LateResolver.end()) {
541 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
542 LateResolver.erase(I);
546 // ResolveTypes - At this point, all types should be resolved. Any that aren't
549 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
550 if (!LateResolveTypes.empty()) {
551 const ValID &DID = LateResolveTypes.begin()->first;
553 if (DID.Type == ValID::NameVal)
554 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
556 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
560 // setValueName - Set the specified value to the name given. The name may be
561 // null potentially, in which case this is a noop. The string passed in is
562 // assumed to be a malloc'd string buffer, and is free'd by this function.
564 static void setValueName(Value *V, char *NameStr) {
566 std::string Name(NameStr); // Copy string
567 free(NameStr); // Free old string
569 if (V->getType() == Type::VoidTy)
570 ThrowException("Can't assign name '" + Name+"' to value with void type!");
572 assert(inFunctionScope() && "Must be in function scope!");
573 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
574 if (ST.lookup(V->getType(), Name))
575 ThrowException("Redefinition of value named '" + Name + "' in the '" +
576 V->getType()->getDescription() + "' type plane!");
579 V->setName(Name, &ST);
583 // setValueNameMergingDuplicates - Set the specified value to the name given.
584 // The name may be null potentially, in which case this is a noop. The string
585 // passed in is assumed to be a malloc'd string buffer, and is free'd by this
588 // This function returns true if the value has already been defined, but is
589 // allowed to be redefined in the specified context. If the name is a new name
590 // for the typeplane, false is returned.
592 static bool setValueNameMergingDuplicates(Value *V, char *NameStr) {
593 assert(V->getType() != Type::VoidTy && "Global or constant of type void?");
595 if (NameStr == 0) return false;
597 std::string Name(NameStr); // Copy string
598 free(NameStr); // Free old string
600 // FIXME: If we eliminated the function constant pool (which we should), this
601 // would just unconditionally look at the module symtab.
602 SymbolTable &ST = inFunctionScope() ?
603 CurFun.CurrentFunction->getSymbolTable() :
604 CurModule.CurrentModule->getSymbolTable();
606 Value *Existing = ST.lookup(V->getType(), Name);
607 if (Existing) { // Inserting a name that is already defined???
608 // We are a simple redefinition of a value, check to see if it is defined
609 // the same as the old one...
610 if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
611 // We are allowed to redefine a global variable in two circumstances:
612 // 1. If at least one of the globals is uninitialized or
613 // 2. If both initializers have the same value.
615 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
616 if (!EGV->hasInitializer() || !GV->hasInitializer() ||
617 EGV->getInitializer() == GV->getInitializer()) {
619 // Make sure the existing global version gets the initializer! Make
620 // sure that it also gets marked const if the new version is.
621 if (GV->hasInitializer() && !EGV->hasInitializer())
622 EGV->setInitializer(GV->getInitializer());
623 if (GV->isConstant())
624 EGV->setConstant(true);
625 EGV->setLinkage(GV->getLinkage());
627 delete GV; // Destroy the duplicate!
628 return true; // They are equivalent!
631 } else if (const Constant *C = dyn_cast<Constant>(Existing)) {
632 if (C == V) return true; // Constants are equal to themselves
635 ThrowException("Redefinition of value named '" + Name + "' in the '" +
636 V->getType()->getDescription() + "' type plane!");
640 V->setName(Name, &ST);
646 // setTypeName - Set the specified type to the name given. The name may be
647 // null potentially, in which case this is a noop. The string passed in is
648 // assumed to be a malloc'd string buffer, and is freed by this function.
650 // This function returns true if the type has already been defined, but is
651 // allowed to be redefined in the specified context. If the name is a new name
652 // for the type plane, it is inserted and false is returned.
653 static bool setTypeName(const Type *T, char *NameStr) {
654 if (NameStr == 0) return false;
656 std::string Name(NameStr); // Copy string
657 free(NameStr); // Free old string
659 // We don't allow assigning names to void type
660 if (T == Type::VoidTy)
661 ThrowException("Can't assign name '" + Name + "' to the void type!");
663 SymbolTable &ST = inFunctionScope() ?
664 CurFun.CurrentFunction->getSymbolTable() :
665 CurModule.CurrentModule->getSymbolTable();
667 // Inserting a name that is already defined???
668 if (Type *Existing = ST.lookupType(Name)) {
669 // There is only one case where this is allowed: when we are refining an
670 // opaque type. In this case, Existing will be an opaque type.
671 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
672 // We ARE replacing an opaque type!
673 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
677 // Otherwise, this is an attempt to redefine a type. That's okay if
678 // the redefinition is identical to the original. This will be so if
679 // Existing and T point to the same Type object. In this one case we
680 // allow the equivalent redefinition.
681 if (Existing == T) return true; // Yes, it's equal.
683 // Any other kind of (non-equivalent) redefinition is an error.
684 ThrowException("Redefinition of type named '" + Name + "' in the '" +
685 T->getDescription() + "' type plane!");
688 // Okay, its a newly named type. Set its name.
689 if (!Name.empty()) ST.insert(Name, T);
694 //===----------------------------------------------------------------------===//
695 // Code for handling upreferences in type names...
698 // TypeContains - Returns true if Ty directly contains E in it.
700 static bool TypeContains(const Type *Ty, const Type *E) {
701 return find(Ty->subtype_begin(), Ty->subtype_end(), E) != Ty->subtype_end();
706 // NestingLevel - The number of nesting levels that need to be popped before
707 // this type is resolved.
708 unsigned NestingLevel;
710 // LastContainedTy - This is the type at the current binding level for the
711 // type. Every time we reduce the nesting level, this gets updated.
712 const Type *LastContainedTy;
714 // UpRefTy - This is the actual opaque type that the upreference is
718 UpRefRecord(unsigned NL, OpaqueType *URTy)
719 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
723 // UpRefs - A list of the outstanding upreferences that need to be resolved.
724 static std::vector<UpRefRecord> UpRefs;
726 /// HandleUpRefs - Every time we finish a new layer of types, this function is
727 /// called. It loops through the UpRefs vector, which is a list of the
728 /// currently active types. For each type, if the up reference is contained in
729 /// the newly completed type, we decrement the level count. When the level
730 /// count reaches zero, the upreferenced type is the type that is passed in:
731 /// thus we can complete the cycle.
733 static PATypeHolder HandleUpRefs(const Type *ty) {
734 if (!ty->isAbstract()) return ty;
736 UR_OUT("Type '" << Ty->getDescription() <<
737 "' newly formed. Resolving upreferences.\n" <<
738 UpRefs.size() << " upreferences active!\n");
740 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
741 // to zero), we resolve them all together before we resolve them to Ty. At
742 // the end of the loop, if there is anything to resolve to Ty, it will be in
744 OpaqueType *TypeToResolve = 0;
746 for (unsigned i = 0; i != UpRefs.size(); ++i) {
747 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
748 << UpRefs[i].second->getDescription() << ") = "
749 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
750 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
751 // Decrement level of upreference
752 unsigned Level = --UpRefs[i].NestingLevel;
753 UpRefs[i].LastContainedTy = Ty;
754 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
755 if (Level == 0) { // Upreference should be resolved!
756 if (!TypeToResolve) {
757 TypeToResolve = UpRefs[i].UpRefTy;
759 UR_OUT(" * Resolving upreference for "
760 << UpRefs[i].second->getDescription() << "\n";
761 std::string OldName = UpRefs[i].UpRefTy->getDescription());
762 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
763 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
764 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
766 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
767 --i; // Do not skip the next element...
773 UR_OUT(" * Resolving upreference for "
774 << UpRefs[i].second->getDescription() << "\n";
775 std::string OldName = TypeToResolve->getDescription());
776 TypeToResolve->refineAbstractTypeTo(Ty);
783 //===----------------------------------------------------------------------===//
784 // RunVMAsmParser - Define an interface to this parser
785 //===----------------------------------------------------------------------===//
787 Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
789 CurFilename = Filename;
790 llvmAsmlineno = 1; // Reset the current line number...
791 ObsoleteVarArgs = false;
793 // Allocate a new module to read
794 CurModule.CurrentModule = new Module(Filename);
796 yyparse(); // Parse the file, potentially throwing exception
798 Module *Result = ParserResult;
800 // Check to see if they called va_start but not va_arg..
801 if (!ObsoleteVarArgs)
802 if (Function *F = Result->getNamedFunction("llvm.va_start"))
803 if (F->asize() == 1) {
804 std::cerr << "WARNING: this file uses obsolete features. "
805 << "Assemble and disassemble to update it.\n";
806 ObsoleteVarArgs = true;
809 if (ObsoleteVarArgs) {
810 // If the user is making use of obsolete varargs intrinsics, adjust them for
812 if (Function *F = Result->getNamedFunction("llvm.va_start")) {
813 assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
815 const Type *RetTy = F->getFunctionType()->getParamType(0);
816 RetTy = cast<PointerType>(RetTy)->getElementType();
817 Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
819 while (!F->use_empty()) {
820 CallInst *CI = cast<CallInst>(F->use_back());
821 Value *V = new CallInst(NF, "", CI);
822 new StoreInst(V, CI->getOperand(1), CI);
823 CI->getParent()->getInstList().erase(CI);
825 Result->getFunctionList().erase(F);
828 if (Function *F = Result->getNamedFunction("llvm.va_end")) {
829 assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
830 const Type *ArgTy = F->getFunctionType()->getParamType(0);
831 ArgTy = cast<PointerType>(ArgTy)->getElementType();
832 Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
835 while (!F->use_empty()) {
836 CallInst *CI = cast<CallInst>(F->use_back());
837 Value *V = new LoadInst(CI->getOperand(1), "", CI);
838 new CallInst(NF, V, "", CI);
839 CI->getParent()->getInstList().erase(CI);
841 Result->getFunctionList().erase(F);
844 if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
845 assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
846 const Type *ArgTy = F->getFunctionType()->getParamType(0);
847 ArgTy = cast<PointerType>(ArgTy)->getElementType();
848 Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
851 while (!F->use_empty()) {
852 CallInst *CI = cast<CallInst>(F->use_back());
853 Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
854 new StoreInst(V, CI->getOperand(1), CI);
855 CI->getParent()->getInstList().erase(CI);
857 Result->getFunctionList().erase(F);
861 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
867 } // End llvm namespace
869 using namespace llvm;
874 llvm::Module *ModuleVal;
875 llvm::Function *FunctionVal;
876 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
877 llvm::BasicBlock *BasicBlockVal;
878 llvm::TerminatorInst *TermInstVal;
879 llvm::Instruction *InstVal;
880 llvm::Constant *ConstVal;
882 const llvm::Type *PrimType;
883 llvm::PATypeHolder *TypeVal;
884 llvm::Value *ValueVal;
886 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
887 std::vector<llvm::Value*> *ValueList;
888 std::list<llvm::PATypeHolder> *TypeList;
889 std::list<std::pair<llvm::Value*,
890 llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
891 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
892 std::vector<llvm::Constant*> *ConstVector;
894 llvm::GlobalValue::LinkageTypes Linkage;
902 char *StrVal; // This memory is strdup'd!
903 llvm::ValID ValIDVal; // strdup'd memory maybe!
905 llvm::Instruction::BinaryOps BinaryOpVal;
906 llvm::Instruction::TermOps TermOpVal;
907 llvm::Instruction::MemoryOps MemOpVal;
908 llvm::Instruction::OtherOps OtherOpVal;
909 llvm::Module::Endianness Endianness;
912 %type <ModuleVal> Module FunctionList
913 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
914 %type <BasicBlockVal> BasicBlock InstructionList
915 %type <TermInstVal> BBTerminatorInst
916 %type <InstVal> Inst InstVal MemoryInst
917 %type <ConstVal> ConstVal ConstExpr
918 %type <ConstVector> ConstVector
919 %type <ArgList> ArgList ArgListH
920 %type <ArgVal> ArgVal
921 %type <PHIList> PHIList
922 %type <ValueList> ValueRefList ValueRefListE // For call param lists
923 %type <ValueList> IndexList // For GEP derived indices
924 %type <TypeList> TypeListI ArgTypeListI
925 %type <JumpTable> JumpTable
926 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
927 %type <BoolVal> OptVolatile // 'volatile' or not
928 %type <Linkage> OptLinkage
929 %type <Endianness> BigOrLittle
931 // ValueRef - Unresolved reference to a definition or BB
932 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
933 %type <ValueVal> ResolvedVal // <type> <valref> pair
934 // Tokens and types for handling constant integer values
936 // ESINT64VAL - A negative number within long long range
937 %token <SInt64Val> ESINT64VAL
939 // EUINT64VAL - A positive number within uns. long long range
940 %token <UInt64Val> EUINT64VAL
941 %type <SInt64Val> EINT64VAL
943 %token <SIntVal> SINTVAL // Signed 32 bit ints...
944 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
945 %type <SIntVal> INTVAL
946 %token <FPVal> FPVAL // Float or Double constant
949 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
950 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
951 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
952 %token <PrimType> FLOAT DOUBLE TYPE LABEL
954 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
955 %type <StrVal> Name OptName OptAssign
958 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
959 %token DECLARE GLOBAL CONSTANT VOLATILE
960 %token TO DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE WEAK APPENDING
961 %token OPAQUE NOT EXTERNAL TARGET ENDIAN POINTERSIZE LITTLE BIG
963 // Basic Block Terminating Operators
964 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND
967 %type <BinaryOpVal> BinaryOps // all the binary operators
968 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
969 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
970 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
972 // Memory Instructions
973 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
976 %type <OtherOpVal> ShiftOps
977 %token <OtherOpVal> PHI_TOK CALL CAST SELECT SHL SHR VAARG VANEXT
978 %token VA_ARG // FIXME: OBSOLETE
983 // Handle constant integer size restriction and conversion...
987 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
988 ThrowException("Value too large for type!");
993 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
994 EINT64VAL : EUINT64VAL {
995 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
996 ThrowException("Value too large for type!");
1000 // Operations that are notably excluded from this list include:
1001 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1003 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1004 LogicalOps : AND | OR | XOR;
1005 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1006 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
1008 ShiftOps : SHL | SHR;
1010 // These are some types that allow classification if we only want a particular
1011 // thing... for example, only a signed, unsigned, or integral type.
1012 SIntType : LONG | INT | SHORT | SBYTE;
1013 UIntType : ULONG | UINT | USHORT | UBYTE;
1014 IntType : SIntType | UIntType;
1015 FPType : FLOAT | DOUBLE;
1017 // OptAssign - Value producing statements have an optional assignment component
1018 OptAssign : Name '=' {
1025 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1026 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1027 WEAK { $$ = GlobalValue::WeakLinkage; } |
1028 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1029 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1031 //===----------------------------------------------------------------------===//
1032 // Types includes all predefined types... except void, because it can only be
1033 // used in specific contexts (function returning void for example). To have
1034 // access to it, a user must explicitly use TypesV.
1037 // TypesV includes all of 'Types', but it also includes the void type.
1038 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1039 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1042 if (!UpRefs.empty())
1043 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
1048 // Derived types are added later...
1050 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1051 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1053 $$ = new PATypeHolder(OpaqueType::get());
1056 $$ = new PATypeHolder($1);
1058 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1059 $$ = new PATypeHolder(getTypeVal($1));
1062 // Include derived types in the Types production.
1064 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1065 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1066 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1067 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1068 $$ = new PATypeHolder(OT);
1069 UR_OUT("New Upreference!\n");
1071 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1072 std::vector<const Type*> Params;
1073 mapto($3->begin(), $3->end(), std::back_inserter(Params),
1074 std::mem_fun_ref(&PATypeHolder::get));
1075 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1076 if (isVarArg) Params.pop_back();
1078 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1079 delete $3; // Delete the argument list
1080 delete $1; // Delete the return type handle
1082 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1083 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1086 | '{' TypeListI '}' { // Structure type?
1087 std::vector<const Type*> Elements;
1088 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
1089 std::mem_fun_ref(&PATypeHolder::get));
1091 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1094 | '{' '}' { // Empty structure type?
1095 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1097 | UpRTypes '*' { // Pointer type?
1098 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1102 // TypeList - Used for struct declarations and as a basis for function type
1103 // declaration type lists
1105 TypeListI : UpRTypes {
1106 $$ = new std::list<PATypeHolder>();
1107 $$->push_back(*$1); delete $1;
1109 | TypeListI ',' UpRTypes {
1110 ($$=$1)->push_back(*$3); delete $3;
1113 // ArgTypeList - List of types for a function type declaration...
1114 ArgTypeListI : TypeListI
1115 | TypeListI ',' DOTDOTDOT {
1116 ($$=$1)->push_back(Type::VoidTy);
1119 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1122 $$ = new std::list<PATypeHolder>();
1125 // ConstVal - The various declarations that go into the constant pool. This
1126 // production is used ONLY to represent constants that show up AFTER a 'const',
1127 // 'constant' or 'global' token at global scope. Constants that can be inlined
1128 // into other expressions (such as integers and constexprs) are handled by the
1129 // ResolvedVal, ValueRef and ConstValueRef productions.
1131 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1132 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1134 ThrowException("Cannot make array constant with type: '" +
1135 (*$1)->getDescription() + "'!");
1136 const Type *ETy = ATy->getElementType();
1137 int NumElements = ATy->getNumElements();
1139 // Verify that we have the correct size...
1140 if (NumElements != -1 && NumElements != (int)$3->size())
1141 ThrowException("Type mismatch: constant sized array initialized with " +
1142 utostr($3->size()) + " arguments, but has size of " +
1143 itostr(NumElements) + "!");
1145 // Verify all elements are correct type!
1146 for (unsigned i = 0; i < $3->size(); i++) {
1147 if (ETy != (*$3)[i]->getType())
1148 ThrowException("Element #" + utostr(i) + " is not of type '" +
1149 ETy->getDescription() +"' as required!\nIt is of type '"+
1150 (*$3)[i]->getType()->getDescription() + "'.");
1153 $$ = ConstantArray::get(ATy, *$3);
1154 delete $1; delete $3;
1157 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1159 ThrowException("Cannot make array constant with type: '" +
1160 (*$1)->getDescription() + "'!");
1162 int NumElements = ATy->getNumElements();
1163 if (NumElements != -1 && NumElements != 0)
1164 ThrowException("Type mismatch: constant sized array initialized with 0"
1165 " arguments, but has size of " + itostr(NumElements) +"!");
1166 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1169 | Types 'c' STRINGCONSTANT {
1170 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1172 ThrowException("Cannot make array constant with type: '" +
1173 (*$1)->getDescription() + "'!");
1175 int NumElements = ATy->getNumElements();
1176 const Type *ETy = ATy->getElementType();
1177 char *EndStr = UnEscapeLexed($3, true);
1178 if (NumElements != -1 && NumElements != (EndStr-$3))
1179 ThrowException("Can't build string constant of size " +
1180 itostr((int)(EndStr-$3)) +
1181 " when array has size " + itostr(NumElements) + "!");
1182 std::vector<Constant*> Vals;
1183 if (ETy == Type::SByteTy) {
1184 for (char *C = $3; C != EndStr; ++C)
1185 Vals.push_back(ConstantSInt::get(ETy, *C));
1186 } else if (ETy == Type::UByteTy) {
1187 for (char *C = $3; C != EndStr; ++C)
1188 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1191 ThrowException("Cannot build string arrays of non byte sized elements!");
1194 $$ = ConstantArray::get(ATy, Vals);
1197 | Types '{' ConstVector '}' {
1198 const StructType *STy = dyn_cast<StructType>($1->get());
1200 ThrowException("Cannot make struct constant with type: '" +
1201 (*$1)->getDescription() + "'!");
1203 if ($3->size() != STy->getNumContainedTypes())
1204 ThrowException("Illegal number of initializers for structure type!");
1206 // Check to ensure that constants are compatible with the type initializer!
1207 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1208 if ((*$3)[i]->getType() != STy->getElementType(i))
1209 ThrowException("Expected type '" +
1210 STy->getElementType(i)->getDescription() +
1211 "' for element #" + utostr(i) +
1212 " of structure initializer!");
1214 $$ = ConstantStruct::get(STy, *$3);
1215 delete $1; delete $3;
1218 const StructType *STy = dyn_cast<StructType>($1->get());
1220 ThrowException("Cannot make struct constant with type: '" +
1221 (*$1)->getDescription() + "'!");
1223 if (STy->getNumContainedTypes() != 0)
1224 ThrowException("Illegal number of initializers for structure type!");
1226 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1230 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1232 ThrowException("Cannot make null pointer constant with type: '" +
1233 (*$1)->getDescription() + "'!");
1235 $$ = ConstantPointerNull::get(PTy);
1238 | Types SymbolicValueRef {
1239 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1241 ThrowException("Global const reference must be a pointer type!");
1243 // ConstExprs can exist in the body of a function, thus creating
1244 // ConstantPointerRefs whenever they refer to a variable. Because we are in
1245 // the context of a function, getValNonImprovising will search the functions
1246 // symbol table instead of the module symbol table for the global symbol,
1247 // which throws things all off. To get around this, we just tell
1248 // getValNonImprovising that we are at global scope here.
1250 Function *SavedCurFn = CurFun.CurrentFunction;
1251 CurFun.CurrentFunction = 0;
1253 Value *V = getValNonImprovising(Ty, $2);
1255 CurFun.CurrentFunction = SavedCurFn;
1257 // If this is an initializer for a constant pointer, which is referencing a
1258 // (currently) undefined variable, create a stub now that shall be replaced
1259 // in the future with the right type of variable.
1262 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1263 const PointerType *PT = cast<PointerType>(Ty);
1265 // First check to see if the forward references value is already created!
1266 PerModuleInfo::GlobalRefsType::iterator I =
1267 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1269 if (I != CurModule.GlobalRefs.end()) {
1270 V = I->second; // Placeholder already exists, use it...
1273 // Create a placeholder for the global variable reference...
1274 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
1276 GlobalValue::ExternalLinkage);
1277 // Keep track of the fact that we have a forward ref to recycle it
1278 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1280 // Must temporarily push this value into the module table...
1281 CurModule.CurrentModule->getGlobalList().push_back(GV);
1286 GlobalValue *GV = cast<GlobalValue>(V);
1287 $$ = ConstantPointerRef::get(GV);
1288 delete $1; // Free the type handle
1291 if ($1->get() != $2->getType())
1292 ThrowException("Mismatched types for constant expression!");
1296 | Types ZEROINITIALIZER {
1297 $$ = Constant::getNullValue($1->get());
1301 ConstVal : SIntType EINT64VAL { // integral constants
1302 if (!ConstantSInt::isValueValidForType($1, $2))
1303 ThrowException("Constant value doesn't fit in type!");
1304 $$ = ConstantSInt::get($1, $2);
1306 | UIntType EUINT64VAL { // integral constants
1307 if (!ConstantUInt::isValueValidForType($1, $2))
1308 ThrowException("Constant value doesn't fit in type!");
1309 $$ = ConstantUInt::get($1, $2);
1311 | BOOL TRUETOK { // Boolean constants
1312 $$ = ConstantBool::True;
1314 | BOOL FALSETOK { // Boolean constants
1315 $$ = ConstantBool::False;
1317 | FPType FPVAL { // Float & Double constants
1318 $$ = ConstantFP::get($1, $2);
1322 ConstExpr: CAST '(' ConstVal TO Types ')' {
1323 if (!$3->getType()->isFirstClassType())
1324 ThrowException("cast constant expression from a non-primitive type: '" +
1325 $3->getType()->getDescription() + "'!");
1326 if (!$5->get()->isFirstClassType())
1327 ThrowException("cast constant expression to a non-primitive type: '" +
1328 $5->get()->getDescription() + "'!");
1329 $$ = ConstantExpr::getCast($3, $5->get());
1332 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1333 if (!isa<PointerType>($3->getType()))
1334 ThrowException("GetElementPtr requires a pointer operand!");
1336 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1337 // indices to uint struct indices for compatibility.
1338 generic_gep_type_iterator<std::vector<Value*>::iterator>
1339 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1340 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1341 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1342 if (isa<StructType>(*GTI)) // Only change struct indices
1343 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1344 if (CUI->getType() == Type::UByteTy)
1345 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1348 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1350 ThrowException("Index list invalid for constant getelementptr!");
1352 std::vector<Constant*> IdxVec;
1353 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1354 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1355 IdxVec.push_back(C);
1357 ThrowException("Indices to constant getelementptr must be constants!");
1361 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1363 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1364 if ($3->getType() != Type::BoolTy)
1365 ThrowException("Select condition must be of boolean type!");
1366 if ($5->getType() != $7->getType())
1367 ThrowException("Select operand types must match!");
1368 $$ = ConstantExpr::getSelect($3, $5, $7);
1370 | BinaryOps '(' ConstVal ',' ConstVal ')' {
1371 if ($3->getType() != $5->getType())
1372 ThrowException("Binary operator types must match!");
1373 $$ = ConstantExpr::get($1, $3, $5);
1375 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1376 if ($5->getType() != Type::UByteTy)
1377 ThrowException("Shift count for shift constant must be unsigned byte!");
1378 if (!$3->getType()->isInteger())
1379 ThrowException("Shift constant expression requires integer operand!");
1380 $$ = ConstantExpr::get($1, $3, $5);
1384 // ConstVector - A list of comma separated constants.
1385 ConstVector : ConstVector ',' ConstVal {
1386 ($$ = $1)->push_back($3);
1389 $$ = new std::vector<Constant*>();
1394 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1395 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1398 //===----------------------------------------------------------------------===//
1399 // Rules to match Modules
1400 //===----------------------------------------------------------------------===//
1402 // Module rule: Capture the result of parsing the whole file into a result
1405 Module : FunctionList {
1406 $$ = ParserResult = $1;
1407 CurModule.ModuleDone();
1410 // FunctionList - A list of functions, preceeded by a constant pool.
1412 FunctionList : FunctionList Function {
1414 CurFun.FunctionDone();
1416 | FunctionList FunctionProto {
1419 | FunctionList IMPLEMENTATION {
1423 $$ = CurModule.CurrentModule;
1424 // Resolve circular types before we parse the body of the module
1425 ResolveTypes(CurModule.LateResolveTypes);
1428 // ConstPool - Constants with optional names assigned to them.
1429 ConstPool : ConstPool OptAssign CONST ConstVal {
1430 // FIXME: THIS SHOULD REALLY BE ELIMINATED. It is totally unneeded.
1431 if (!setValueNameMergingDuplicates($4, $2))
1434 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1435 // Eagerly resolve types. This is not an optimization, this is a
1436 // requirement that is due to the fact that we could have this:
1438 // %list = type { %list * }
1439 // %list = type { %list * } ; repeated type decl
1441 // If types are not resolved eagerly, then the two types will not be
1442 // determined to be the same type!
1444 ResolveTypeTo($2, *$4);
1446 if (!setTypeName(*$4, $2) && !$2) {
1447 // If this is a named type that is not a redefinition, add it to the slot
1449 if (inFunctionScope())
1450 CurFun.Types.push_back(*$4);
1452 CurModule.Types.push_back(*$4);
1457 | ConstPool FunctionProto { // Function prototypes can be in const pool
1459 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1460 const Type *Ty = $5->getType();
1461 // Global declarations appear in Constant Pool
1462 Constant *Initializer = $5;
1463 if (Initializer == 0)
1464 ThrowException("Global value initializer is not a constant!");
1466 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1467 if (!setValueNameMergingDuplicates(GV, $2)) { // If not redefining...
1468 CurModule.CurrentModule->getGlobalList().push_back(GV);
1469 int Slot = InsertValue(GV, CurModule.Values);
1472 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1474 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1475 (char*)GV->getName().c_str()));
1479 | ConstPool OptAssign EXTERNAL GlobalType Types {
1480 const Type *Ty = *$5;
1481 // Global declarations appear in Constant Pool
1482 GlobalVariable *GV = new GlobalVariable(Ty,$4,GlobalValue::ExternalLinkage);
1483 if (!setValueNameMergingDuplicates(GV, $2)) { // If not redefining...
1484 CurModule.CurrentModule->getGlobalList().push_back(GV);
1485 int Slot = InsertValue(GV, CurModule.Values);
1488 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1490 assert(GV->hasName() && "Not named and not numbered!?");
1491 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1492 (char*)GV->getName().c_str()));
1497 | ConstPool TARGET TargetDefinition {
1499 | /* empty: end of list */ {
1504 BigOrLittle : BIG { $$ = Module::BigEndian; };
1505 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1507 TargetDefinition : ENDIAN '=' BigOrLittle {
1508 CurModule.CurrentModule->setEndianness($3);
1510 | POINTERSIZE '=' EUINT64VAL {
1512 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1514 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1516 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1520 //===----------------------------------------------------------------------===//
1521 // Rules to match Function Headers
1522 //===----------------------------------------------------------------------===//
1524 Name : VAR_ID | STRINGCONSTANT;
1525 OptName : Name | /*empty*/ { $$ = 0; };
1527 ArgVal : Types OptName {
1528 if (*$1 == Type::VoidTy)
1529 ThrowException("void typed arguments are invalid!");
1530 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1533 ArgListH : ArgListH ',' ArgVal {
1539 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1544 ArgList : ArgListH {
1547 | ArgListH ',' DOTDOTDOT {
1549 $$->push_back(std::pair<PATypeHolder*,
1550 char*>(new PATypeHolder(Type::VoidTy), 0));
1553 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1554 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1560 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1562 std::string FunctionName($2);
1564 if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1565 ThrowException("LLVM functions cannot return aggregate types!");
1567 std::vector<const Type*> ParamTypeList;
1568 if ($4) { // If there are arguments...
1569 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1570 I != $4->end(); ++I)
1571 ParamTypeList.push_back(I->first->get());
1574 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1575 if (isVarArg) ParamTypeList.pop_back();
1577 const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1578 const PointerType *PFT = PointerType::get(FT);
1582 // Is the function already in symtab?
1583 if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1584 // Yes it is. If this is the case, either we need to be a forward decl,
1585 // or it needs to be.
1586 if (!CurFun.isDeclare && !Fn->isExternal())
1587 ThrowException("Redefinition of function '" + FunctionName + "'!");
1589 // Make sure to strip off any argument names so we can't get conflicts...
1590 for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1593 } else { // Not already defined?
1594 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1595 CurModule.CurrentModule);
1596 InsertValue(Fn, CurModule.Values);
1597 CurModule.DeclareNewGlobalValue(Fn, ValID::create($2));
1599 free($2); // Free strdup'd memory!
1601 CurFun.FunctionStart(Fn);
1603 // Add all of the arguments we parsed to the function...
1604 if ($4) { // Is null if empty...
1605 if (isVarArg) { // Nuke the last entry
1606 assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1607 "Not a varargs marker!");
1608 delete $4->back().first;
1609 $4->pop_back(); // Delete the last entry
1611 Function::aiterator ArgIt = Fn->abegin();
1612 for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1613 I != $4->end(); ++I, ++ArgIt) {
1614 delete I->first; // Delete the typeholder...
1616 setValueName(ArgIt, I->second); // Insert arg into symtab...
1620 delete $4; // We're now done with the argument list
1624 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1626 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1627 $$ = CurFun.CurrentFunction;
1629 // Make sure that we keep track of the linkage type even if there was a
1630 // previous "declare".
1633 // Resolve circular types before we parse the body of the function.
1634 ResolveTypes(CurFun.LateResolveTypes);
1637 END : ENDTOK | '}'; // Allow end of '}' to end a function
1639 Function : BasicBlockList END {
1643 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1644 $$ = CurFun.CurrentFunction;
1645 CurFun.FunctionDone();
1648 //===----------------------------------------------------------------------===//
1649 // Rules to match Basic Blocks
1650 //===----------------------------------------------------------------------===//
1652 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1653 $$ = ValID::create($1);
1656 $$ = ValID::create($1);
1658 | FPVAL { // Perhaps it's an FP constant?
1659 $$ = ValID::create($1);
1662 $$ = ValID::create(ConstantBool::True);
1665 $$ = ValID::create(ConstantBool::False);
1668 $$ = ValID::createNull();
1671 $$ = ValID::create($1);
1674 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1677 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1678 $$ = ValID::create($1);
1680 | Name { // Is it a named reference...?
1681 $$ = ValID::create($1);
1684 // ValueRef - A reference to a definition... either constant or symbolic
1685 ValueRef : SymbolicValueRef | ConstValueRef;
1688 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1689 // type immediately preceeds the value reference, and allows complex constant
1690 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1691 ResolvedVal : Types ValueRef {
1692 $$ = getVal(*$1, $2); delete $1;
1695 BasicBlockList : BasicBlockList BasicBlock {
1698 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1703 // Basic blocks are terminated by branching instructions:
1704 // br, br/cc, switch, ret
1706 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1707 setValueName($3, $2);
1710 $1->getInstList().push_back($3);
1715 InstructionList : InstructionList Inst {
1716 $1->getInstList().push_back($2);
1720 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1723 $$ = CurBB = getBBVal(ValID::create($1), true);
1726 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1727 $$ = new ReturnInst($2);
1729 | RET VOID { // Return with no result...
1730 $$ = new ReturnInst();
1732 | BR LABEL ValueRef { // Unconditional Branch...
1733 $$ = new BranchInst(getBBVal($3));
1734 } // Conditional Branch...
1735 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1736 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1738 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1739 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6));
1742 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1745 S->addCase(I->first, I->second);
1748 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1749 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6));
1752 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO LABEL ValueRef
1753 UNWIND LABEL ValueRef {
1754 const PointerType *PFTy;
1755 const FunctionType *Ty;
1757 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1758 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1759 // Pull out the types of all of the arguments...
1760 std::vector<const Type*> ParamTypes;
1762 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1764 ParamTypes.push_back((*I)->getType());
1767 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1768 if (isVarArg) ParamTypes.pop_back();
1770 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1771 PFTy = PointerType::get(Ty);
1774 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1776 BasicBlock *Normal = getBBVal($9);
1777 BasicBlock *Except = getBBVal($12);
1779 // Create the call node...
1780 if (!$5) { // Has no arguments?
1781 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1782 } else { // Has arguments?
1783 // Loop through FunctionType's arguments and ensure they are specified
1786 FunctionType::param_iterator I = Ty->param_begin();
1787 FunctionType::param_iterator E = Ty->param_end();
1788 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1790 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1791 if ((*ArgI)->getType() != *I)
1792 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1793 (*I)->getDescription() + "'!");
1795 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1796 ThrowException("Invalid number of parameters detected!");
1798 $$ = new InvokeInst(V, Normal, Except, *$5);
1804 $$ = new UnwindInst();
1809 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1811 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1813 ThrowException("May only switch on a constant pool value!");
1815 $$->push_back(std::make_pair(V, getBBVal($6)));
1817 | IntType ConstValueRef ',' LABEL ValueRef {
1818 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1819 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1822 ThrowException("May only switch on a constant pool value!");
1824 $$->push_back(std::make_pair(V, getBBVal($5)));
1827 Inst : OptAssign InstVal {
1828 // Is this definition named?? if so, assign the name...
1829 setValueName($2, $1);
1834 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1835 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1836 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
1839 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1841 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1846 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1847 $$ = new std::vector<Value*>();
1850 | ValueRefList ',' ResolvedVal {
1855 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1856 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1858 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1859 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1860 ThrowException("Arithmetic operator requires integer or FP operands!");
1861 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1863 ThrowException("binary operator returned null!");
1866 | LogicalOps Types ValueRef ',' ValueRef {
1867 if (!(*$2)->isIntegral())
1868 ThrowException("Logical operator requires integral operands!");
1869 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1871 ThrowException("binary operator returned null!");
1874 | SetCondOps Types ValueRef ',' ValueRef {
1875 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1877 ThrowException("binary operator returned null!");
1881 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1882 << " Replacing with 'xor'.\n";
1884 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1886 ThrowException("Expected integral type for not instruction!");
1888 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1890 ThrowException("Could not create a xor instruction!");
1892 | ShiftOps ResolvedVal ',' ResolvedVal {
1893 if ($4->getType() != Type::UByteTy)
1894 ThrowException("Shift amount must be ubyte!");
1895 if (!$2->getType()->isInteger())
1896 ThrowException("Shift constant expression requires integer operand!");
1897 $$ = new ShiftInst($1, $2, $4);
1899 | CAST ResolvedVal TO Types {
1900 if (!$4->get()->isFirstClassType())
1901 ThrowException("cast instruction to a non-primitive type: '" +
1902 $4->get()->getDescription() + "'!");
1903 $$ = new CastInst($2, *$4);
1906 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1907 if ($2->getType() != Type::BoolTy)
1908 ThrowException("select condition must be boolean!");
1909 if ($4->getType() != $6->getType())
1910 ThrowException("select value types should match!");
1911 $$ = new SelectInst($2, $4, $6);
1913 | VA_ARG ResolvedVal ',' Types {
1914 // FIXME: This is emulation code for an obsolete syntax. This should be
1915 // removed at some point.
1916 if (!ObsoleteVarArgs) {
1917 std::cerr << "WARNING: this file uses obsolete features. "
1918 << "Assemble and disassemble to update it.\n";
1919 ObsoleteVarArgs = true;
1922 // First, load the valist...
1923 Instruction *CurVAList = new LoadInst($2, "");
1924 CurBB->getInstList().push_back(CurVAList);
1926 // Emit the vaarg instruction.
1927 $$ = new VAArgInst(CurVAList, *$4);
1929 // Now we must advance the pointer and update it in memory.
1930 Instruction *TheVANext = new VANextInst(CurVAList, *$4);
1931 CurBB->getInstList().push_back(TheVANext);
1933 CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
1936 | VAARG ResolvedVal ',' Types {
1937 $$ = new VAArgInst($2, *$4);
1940 | VANEXT ResolvedVal ',' Types {
1941 $$ = new VANextInst($2, *$4);
1945 const Type *Ty = $2->front().first->getType();
1946 if (!Ty->isFirstClassType())
1947 ThrowException("PHI node operands must be of first class type!");
1948 $$ = new PHINode(Ty);
1949 $$->op_reserve($2->size()*2);
1950 while ($2->begin() != $2->end()) {
1951 if ($2->front().first->getType() != Ty)
1952 ThrowException("All elements of a PHI node must be of the same type!");
1953 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1956 delete $2; // Free the list...
1958 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1959 const PointerType *PFTy;
1960 const FunctionType *Ty;
1962 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1963 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1964 // Pull out the types of all of the arguments...
1965 std::vector<const Type*> ParamTypes;
1967 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1969 ParamTypes.push_back((*I)->getType());
1972 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1973 if (isVarArg) ParamTypes.pop_back();
1975 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1976 PFTy = PointerType::get(Ty);
1979 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1981 // Create the call node...
1982 if (!$5) { // Has no arguments?
1983 // Make sure no arguments is a good thing!
1984 if (Ty->getNumParams() != 0)
1985 ThrowException("No arguments passed to a function that "
1986 "expects arguments!");
1988 $$ = new CallInst(V, std::vector<Value*>());
1989 } else { // Has arguments?
1990 // Loop through FunctionType's arguments and ensure they are specified
1993 FunctionType::param_iterator I = Ty->param_begin();
1994 FunctionType::param_iterator E = Ty->param_end();
1995 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1997 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1998 if ((*ArgI)->getType() != *I)
1999 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2000 (*I)->getDescription() + "'!");
2002 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2003 ThrowException("Invalid number of parameters detected!");
2005 $$ = new CallInst(V, *$5);
2015 // IndexList - List of indices for GEP based instructions...
2016 IndexList : ',' ValueRefList {
2019 $$ = new std::vector<Value*>();
2022 OptVolatile : VOLATILE {
2030 MemoryInst : MALLOC Types {
2031 $$ = new MallocInst(*$2);
2034 | MALLOC Types ',' UINT ValueRef {
2035 $$ = new MallocInst(*$2, getVal($4, $5));
2039 $$ = new AllocaInst(*$2);
2042 | ALLOCA Types ',' UINT ValueRef {
2043 $$ = new AllocaInst(*$2, getVal($4, $5));
2046 | FREE ResolvedVal {
2047 if (!isa<PointerType>($2->getType()))
2048 ThrowException("Trying to free nonpointer type " +
2049 $2->getType()->getDescription() + "!");
2050 $$ = new FreeInst($2);
2053 | OptVolatile LOAD Types ValueRef {
2054 if (!isa<PointerType>($3->get()))
2055 ThrowException("Can't load from nonpointer type: " +
2056 (*$3)->getDescription());
2057 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2060 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2061 const PointerType *PT = dyn_cast<PointerType>($5->get());
2063 ThrowException("Can't store to a nonpointer type: " +
2064 (*$5)->getDescription());
2065 const Type *ElTy = PT->getElementType();
2066 if (ElTy != $3->getType())
2067 ThrowException("Can't store '" + $3->getType()->getDescription() +
2068 "' into space of type '" + ElTy->getDescription() + "'!");
2070 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2073 | GETELEMENTPTR Types ValueRef IndexList {
2074 if (!isa<PointerType>($2->get()))
2075 ThrowException("getelementptr insn requires pointer operand!");
2077 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2078 // indices to uint struct indices for compatibility.
2079 generic_gep_type_iterator<std::vector<Value*>::iterator>
2080 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2081 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2082 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2083 if (isa<StructType>(*GTI)) // Only change struct indices
2084 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2085 if (CUI->getType() == Type::UByteTy)
2086 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2088 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2089 ThrowException("Invalid getelementptr indices for type '" +
2090 (*$2)->getDescription()+ "'!");
2091 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2092 delete $2; delete $4;
2097 int yyerror(const char *ErrorMsg) {
2099 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2100 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2101 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2102 if (yychar == YYEMPTY || yychar == 0)
2103 errMsg += "end-of-file.";
2105 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2106 ThrowException(errMsg);