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 // HACK ALERT: This variable is used to implement the automatic conversion of
50 // variable argument instructions from their old to new forms. When this
51 // compatiblity "Feature" is removed, this should be too.
53 static BasicBlock *CurBB;
54 static bool ObsoleteVarArgs;
57 // This contains info used when building the body of a function. It is
58 // destroyed when the function is completed.
60 typedef std::vector<Value *> ValueList; // Numbered defs
61 static void ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
62 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
64 static struct PerModuleInfo {
65 Module *CurrentModule;
66 std::map<const Type *, ValueList> Values; // Module level numbered definitions
67 std::map<const Type *,ValueList> LateResolveValues;
68 std::vector<PATypeHolder> Types;
69 std::map<ValID, PATypeHolder> LateResolveTypes;
71 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
72 /// how they were referenced and one which line of the input they came from so
73 /// that we can resolve them later and print error messages as appropriate.
74 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
76 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
77 // references to global values. Global values may be referenced before they
78 // are defined, and if so, the temporary object that they represent is held
79 // here. This is used for forward references of GlobalValues.
81 typedef std::map<std::pair<const PointerType *,
82 ValID>, GlobalValue*> GlobalRefsType;
83 GlobalRefsType GlobalRefs;
86 // If we could not resolve some functions at function compilation time
87 // (calls to functions before they are defined), resolve them now... Types
88 // are resolved when the constant pool has been completely parsed.
90 ResolveDefinitions(LateResolveValues);
92 // Check to make sure that all global value forward references have been
95 if (!GlobalRefs.empty()) {
96 std::string UndefinedReferences = "Unresolved global references exist:\n";
98 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
100 UndefinedReferences += " " + I->first.first->getDescription() + " " +
101 I->first.second.getName() + "\n";
103 ThrowException(UndefinedReferences);
106 Values.clear(); // Clear out function local definitions
112 // GetForwardRefForGlobal - Check to see if there is a forward reference
113 // for this global. If so, remove it from the GlobalRefs map and return it.
114 // If not, just return null.
115 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
116 // Check to see if there is a forward reference to this global variable...
117 // if there is, eliminate it and patch the reference to use the new def'n.
118 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
119 GlobalValue *Ret = 0;
120 if (I != GlobalRefs.end()) {
128 static struct PerFunctionInfo {
129 Function *CurrentFunction; // Pointer to current function being created
131 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
132 std::map<const Type*, ValueList> LateResolveValues;
133 bool isDeclare; // Is this function a forward declararation?
135 /// BBForwardRefs - When we see forward references to basic blocks, keep
136 /// track of them here.
137 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
138 std::vector<BasicBlock*> NumberedBlocks;
141 inline PerFunctionInfo() {
146 inline void FunctionStart(Function *M) {
151 void FunctionDone() {
152 NumberedBlocks.clear();
154 // Any forward referenced blocks left?
155 if (!BBForwardRefs.empty())
156 ThrowException("Undefined reference to label " +
157 BBForwardRefs.begin()->first->getName());
159 // Resolve all forward references now.
160 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
162 Values.clear(); // Clear out function local definitions
166 } CurFun; // Info for the current function...
168 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
171 //===----------------------------------------------------------------------===//
172 // Code to handle definitions of all the types
173 //===----------------------------------------------------------------------===//
175 static int InsertValue(Value *V,
176 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
177 if (V->hasName()) return -1; // Is this a numbered definition?
179 // Yes, insert the value into the value table...
180 ValueList &List = ValueTab[V->getType()];
182 return List.size()-1;
185 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
187 case ValID::NumberVal: // Is it a numbered definition?
188 // Module constants occupy the lowest numbered slots...
189 if ((unsigned)D.Num < CurModule.Types.size())
190 return CurModule.Types[(unsigned)D.Num];
192 case ValID::NameVal: // Is it a named definition?
193 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
194 D.destroy(); // Free old strdup'd memory...
199 ThrowException("Internal parser error: Invalid symbol type reference!");
202 // If we reached here, we referenced either a symbol that we don't know about
203 // or an id number that hasn't been read yet. We may be referencing something
204 // forward, so just create an entry to be resolved later and get to it...
206 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
209 if (inFunctionScope()) {
210 if (D.Type == ValID::NameVal)
211 ThrowException("Reference to an undefined type: '" + D.getName() + "'");
213 ThrowException("Reference to an undefined type: #" + itostr(D.Num));
216 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
217 if (I != CurModule.LateResolveTypes.end())
220 Type *Typ = OpaqueType::get();
221 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
225 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
226 SymbolTable &SymTab =
227 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
228 CurModule.CurrentModule->getSymbolTable();
229 return SymTab.lookup(Ty, Name);
232 // getValNonImprovising - Look up the value specified by the provided type and
233 // the provided ValID. If the value exists and has already been defined, return
234 // it. Otherwise return null.
236 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
237 if (isa<FunctionType>(Ty))
238 ThrowException("Functions are not values and "
239 "must be referenced as pointers");
242 case ValID::NumberVal: { // Is it a numbered definition?
243 unsigned Num = (unsigned)D.Num;
245 // Module constants occupy the lowest numbered slots...
246 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
247 if (VI != CurModule.Values.end()) {
248 if (Num < VI->second.size())
249 return VI->second[Num];
250 Num -= VI->second.size();
253 // Make sure that our type is within bounds
254 VI = CurFun.Values.find(Ty);
255 if (VI == CurFun.Values.end()) return 0;
257 // Check that the number is within bounds...
258 if (VI->second.size() <= Num) return 0;
260 return VI->second[Num];
263 case ValID::NameVal: { // Is it a named definition?
264 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
265 if (N == 0) return 0;
267 D.destroy(); // Free old strdup'd memory...
271 // Check to make sure that "Ty" is an integral type, and that our
272 // value will fit into the specified type...
273 case ValID::ConstSIntVal: // Is it a constant pool reference??
274 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
275 ThrowException("Signed integral constant '" +
276 itostr(D.ConstPool64) + "' is invalid for type '" +
277 Ty->getDescription() + "'!");
278 return ConstantSInt::get(Ty, D.ConstPool64);
280 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
281 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
282 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
283 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
284 "' is invalid or out of range!");
285 } else { // This is really a signed reference. Transmogrify.
286 return ConstantSInt::get(Ty, D.ConstPool64);
289 return ConstantUInt::get(Ty, D.UConstPool64);
292 case ValID::ConstFPVal: // Is it a floating point const pool reference?
293 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
294 ThrowException("FP constant invalid for type!!");
295 return ConstantFP::get(Ty, D.ConstPoolFP);
297 case ValID::ConstNullVal: // Is it a null value?
298 if (!isa<PointerType>(Ty))
299 ThrowException("Cannot create a a non pointer null!");
300 return ConstantPointerNull::get(cast<PointerType>(Ty));
302 case ValID::ConstUndefVal: // Is it an undef value?
303 return UndefValue::get(Ty);
305 case ValID::ConstantVal: // Fully resolved constant?
306 if (D.ConstantValue->getType() != Ty)
307 ThrowException("Constant expression type different from required type!");
308 return D.ConstantValue;
311 assert(0 && "Unhandled case!");
315 assert(0 && "Unhandled case!");
319 // getVal - This function is identical to getValNonImprovising, except that if a
320 // value is not already defined, it "improvises" by creating a placeholder var
321 // that looks and acts just like the requested variable. When the value is
322 // defined later, all uses of the placeholder variable are replaced with the
325 static Value *getVal(const Type *Ty, const ValID &ID) {
326 if (Ty == Type::LabelTy)
327 ThrowException("Cannot use a basic block here");
329 // See if the value has already been defined.
330 Value *V = getValNonImprovising(Ty, ID);
333 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
334 ThrowException("Invalid use of a composite type!");
336 // If we reached here, we referenced either a symbol that we don't know about
337 // or an id number that hasn't been read yet. We may be referencing something
338 // forward, so just create an entry to be resolved later and get to it...
340 V = new Argument(Ty);
342 // Remember where this forward reference came from. FIXME, shouldn't we try
343 // to recycle these things??
344 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
347 if (inFunctionScope())
348 InsertValue(V, CurFun.LateResolveValues);
350 InsertValue(V, CurModule.LateResolveValues);
354 /// getBBVal - This is used for two purposes:
355 /// * If isDefinition is true, a new basic block with the specified ID is being
357 /// * If isDefinition is true, this is a reference to a basic block, which may
358 /// or may not be a forward reference.
360 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
361 assert(inFunctionScope() && "Can't get basic block at global scope!");
366 default: ThrowException("Illegal label reference " + ID.getName());
367 case ValID::NumberVal: // Is it a numbered definition?
368 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
369 CurFun.NumberedBlocks.resize(ID.Num+1);
370 BB = CurFun.NumberedBlocks[ID.Num];
372 case ValID::NameVal: // Is it a named definition?
374 if (Value *N = CurFun.CurrentFunction->
375 getSymbolTable().lookup(Type::LabelTy, Name))
376 BB = cast<BasicBlock>(N);
380 // See if the block has already been defined.
382 // If this is the definition of the block, make sure the existing value was
383 // just a forward reference. If it was a forward reference, there will be
384 // an entry for it in the PlaceHolderInfo map.
385 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
386 // The existing value was a definition, not a forward reference.
387 ThrowException("Redefinition of label " + ID.getName());
389 ID.destroy(); // Free strdup'd memory.
393 // Otherwise this block has not been seen before.
394 BB = new BasicBlock("", CurFun.CurrentFunction);
395 if (ID.Type == ValID::NameVal) {
396 BB->setName(ID.Name);
398 CurFun.NumberedBlocks[ID.Num] = BB;
401 // If this is not a definition, keep track of it so we can use it as a forward
404 // Remember where this forward reference came from.
405 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
407 // The forward declaration could have been inserted anywhere in the
408 // function: insert it into the correct place now.
409 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
410 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
417 //===----------------------------------------------------------------------===//
418 // Code to handle forward references in instructions
419 //===----------------------------------------------------------------------===//
421 // This code handles the late binding needed with statements that reference
422 // values not defined yet... for example, a forward branch, or the PHI node for
425 // This keeps a table (CurFun.LateResolveValues) of all such forward references
426 // and back patchs after we are done.
429 // ResolveDefinitions - If we could not resolve some defs at parsing
430 // time (forward branches, phi functions for loops, etc...) resolve the
433 static void ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
434 std::map<const Type*,ValueList> *FutureLateResolvers) {
435 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
436 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
437 E = LateResolvers.end(); LRI != E; ++LRI) {
438 ValueList &List = LRI->second;
439 while (!List.empty()) {
440 Value *V = List.back();
443 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
444 CurModule.PlaceHolderInfo.find(V);
445 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
447 ValID &DID = PHI->second.first;
449 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
451 V->replaceAllUsesWith(TheRealValue);
453 CurModule.PlaceHolderInfo.erase(PHI);
454 } else if (FutureLateResolvers) {
455 // Functions have their unresolved items forwarded to the module late
457 InsertValue(V, *FutureLateResolvers);
459 if (DID.Type == ValID::NameVal)
460 ThrowException("Reference to an invalid definition: '" +DID.getName()+
461 "' of type '" + V->getType()->getDescription() + "'",
464 ThrowException("Reference to an invalid definition: #" +
465 itostr(DID.Num) + " of type '" +
466 V->getType()->getDescription() + "'",
472 LateResolvers.clear();
475 // ResolveTypeTo - A brand new type was just declared. This means that (if
476 // name is not null) things referencing Name can be resolved. Otherwise, things
477 // refering to the number can be resolved. Do this now.
479 static void ResolveTypeTo(char *Name, const Type *ToTy) {
481 if (Name) D = ValID::create(Name);
482 else D = ValID::create((int)CurModule.Types.size());
484 std::map<ValID, PATypeHolder>::iterator I =
485 CurModule.LateResolveTypes.find(D);
486 if (I != CurModule.LateResolveTypes.end()) {
487 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
488 CurModule.LateResolveTypes.erase(I);
492 // setValueName - Set the specified value to the name given. The name may be
493 // null potentially, in which case this is a noop. The string passed in is
494 // assumed to be a malloc'd string buffer, and is free'd by this function.
496 static void setValueName(Value *V, char *NameStr) {
498 std::string Name(NameStr); // Copy string
499 free(NameStr); // Free old string
501 if (V->getType() == Type::VoidTy)
502 ThrowException("Can't assign name '" + Name+"' to value with void type!");
504 assert(inFunctionScope() && "Must be in function scope!");
505 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
506 if (ST.lookup(V->getType(), Name))
507 ThrowException("Redefinition of value named '" + Name + "' in the '" +
508 V->getType()->getDescription() + "' type plane!");
515 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
516 /// this is a declaration, otherwise it is a definition.
517 static void ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
518 bool isConstantGlobal, const Type *Ty,
519 Constant *Initializer) {
520 if (isa<FunctionType>(Ty))
521 ThrowException("Cannot declare global vars of function type!");
523 const PointerType *PTy = PointerType::get(Ty);
527 Name = NameStr; // Copy string
528 free(NameStr); // Free old string
531 // See if this global value was forward referenced. If so, recycle the
535 ID = ValID::create((char*)Name.c_str());
537 ID = ValID::create((int)CurModule.Values[PTy].size());
540 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
541 // Move the global to the end of the list, from whereever it was
542 // previously inserted.
543 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
544 CurModule.CurrentModule->getGlobalList().remove(GV);
545 CurModule.CurrentModule->getGlobalList().push_back(GV);
546 GV->setInitializer(Initializer);
547 GV->setLinkage(Linkage);
548 GV->setConstant(isConstantGlobal);
549 InsertValue(GV, CurModule.Values);
553 // If this global has a name, check to see if there is already a definition
554 // of this global in the module. If so, merge as appropriate. Note that
555 // this is really just a hack around problems in the CFE. :(
557 // We are a simple redefinition of a value, check to see if it is defined
558 // the same as the old one.
559 if (GlobalVariable *EGV =
560 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
561 // We are allowed to redefine a global variable in two circumstances:
562 // 1. If at least one of the globals is uninitialized or
563 // 2. If both initializers have the same value.
565 if (!EGV->hasInitializer() || !Initializer ||
566 EGV->getInitializer() == Initializer) {
568 // Make sure the existing global version gets the initializer! Make
569 // sure that it also gets marked const if the new version is.
570 if (Initializer && !EGV->hasInitializer())
571 EGV->setInitializer(Initializer);
572 if (isConstantGlobal)
573 EGV->setConstant(true);
574 EGV->setLinkage(Linkage);
578 ThrowException("Redefinition of global variable named '" + Name +
579 "' in the '" + Ty->getDescription() + "' type plane!");
583 // Otherwise there is no existing GV to use, create one now.
585 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
586 CurModule.CurrentModule);
587 InsertValue(GV, CurModule.Values);
590 // setTypeName - Set the specified type to the name given. The name may be
591 // null potentially, in which case this is a noop. The string passed in is
592 // assumed to be a malloc'd string buffer, and is freed by this function.
594 // This function returns true if the type has already been defined, but is
595 // allowed to be redefined in the specified context. If the name is a new name
596 // for the type plane, it is inserted and false is returned.
597 static bool setTypeName(const Type *T, char *NameStr) {
598 assert(!inFunctionScope() && "Can't give types function-local names!");
599 if (NameStr == 0) return false;
601 std::string Name(NameStr); // Copy string
602 free(NameStr); // Free old string
604 // We don't allow assigning names to void type
605 if (T == Type::VoidTy)
606 ThrowException("Can't assign name '" + Name + "' to the void type!");
608 // Set the type name, checking for conflicts as we do so.
609 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
611 if (AlreadyExists) { // Inserting a name that is already defined???
612 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
613 assert(Existing && "Conflict but no matching type?");
615 // There is only one case where this is allowed: when we are refining an
616 // opaque type. In this case, Existing will be an opaque type.
617 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
618 // We ARE replacing an opaque type!
619 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
623 // Otherwise, this is an attempt to redefine a type. That's okay if
624 // the redefinition is identical to the original. This will be so if
625 // Existing and T point to the same Type object. In this one case we
626 // allow the equivalent redefinition.
627 if (Existing == T) return true; // Yes, it's equal.
629 // Any other kind of (non-equivalent) redefinition is an error.
630 ThrowException("Redefinition of type named '" + Name + "' in the '" +
631 T->getDescription() + "' type plane!");
637 //===----------------------------------------------------------------------===//
638 // Code for handling upreferences in type names...
641 // TypeContains - Returns true if Ty directly contains E in it.
643 static bool TypeContains(const Type *Ty, const Type *E) {
644 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
645 E) != Ty->subtype_end();
650 // NestingLevel - The number of nesting levels that need to be popped before
651 // this type is resolved.
652 unsigned NestingLevel;
654 // LastContainedTy - This is the type at the current binding level for the
655 // type. Every time we reduce the nesting level, this gets updated.
656 const Type *LastContainedTy;
658 // UpRefTy - This is the actual opaque type that the upreference is
662 UpRefRecord(unsigned NL, OpaqueType *URTy)
663 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
667 // UpRefs - A list of the outstanding upreferences that need to be resolved.
668 static std::vector<UpRefRecord> UpRefs;
670 /// HandleUpRefs - Every time we finish a new layer of types, this function is
671 /// called. It loops through the UpRefs vector, which is a list of the
672 /// currently active types. For each type, if the up reference is contained in
673 /// the newly completed type, we decrement the level count. When the level
674 /// count reaches zero, the upreferenced type is the type that is passed in:
675 /// thus we can complete the cycle.
677 static PATypeHolder HandleUpRefs(const Type *ty) {
678 if (!ty->isAbstract()) return ty;
680 UR_OUT("Type '" << Ty->getDescription() <<
681 "' newly formed. Resolving upreferences.\n" <<
682 UpRefs.size() << " upreferences active!\n");
684 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
685 // to zero), we resolve them all together before we resolve them to Ty. At
686 // the end of the loop, if there is anything to resolve to Ty, it will be in
688 OpaqueType *TypeToResolve = 0;
690 for (unsigned i = 0; i != UpRefs.size(); ++i) {
691 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
692 << UpRefs[i].second->getDescription() << ") = "
693 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
694 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
695 // Decrement level of upreference
696 unsigned Level = --UpRefs[i].NestingLevel;
697 UpRefs[i].LastContainedTy = Ty;
698 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
699 if (Level == 0) { // Upreference should be resolved!
700 if (!TypeToResolve) {
701 TypeToResolve = UpRefs[i].UpRefTy;
703 UR_OUT(" * Resolving upreference for "
704 << UpRefs[i].second->getDescription() << "\n";
705 std::string OldName = UpRefs[i].UpRefTy->getDescription());
706 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
707 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
708 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
710 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
711 --i; // Do not skip the next element...
717 UR_OUT(" * Resolving upreference for "
718 << UpRefs[i].second->getDescription() << "\n";
719 std::string OldName = TypeToResolve->getDescription());
720 TypeToResolve->refineAbstractTypeTo(Ty);
727 //===----------------------------------------------------------------------===//
728 // RunVMAsmParser - Define an interface to this parser
729 //===----------------------------------------------------------------------===//
731 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
733 CurFilename = Filename;
734 llvmAsmlineno = 1; // Reset the current line number...
735 ObsoleteVarArgs = false;
737 // Allocate a new module to read
738 CurModule.CurrentModule = new Module(Filename);
740 yyparse(); // Parse the file, potentially throwing exception
742 Module *Result = ParserResult;
744 // Check to see if they called va_start but not va_arg..
745 if (!ObsoleteVarArgs)
746 if (Function *F = Result->getNamedFunction("llvm.va_start"))
747 if (F->arg_size() == 1) {
748 std::cerr << "WARNING: this file uses obsolete features. "
749 << "Assemble and disassemble to update it.\n";
750 ObsoleteVarArgs = true;
753 if (ObsoleteVarArgs) {
754 // If the user is making use of obsolete varargs intrinsics, adjust them for
756 if (Function *F = Result->getNamedFunction("llvm.va_start")) {
757 assert(F->arg_size() == 1 && "Obsolete va_start takes 1 argument!");
759 const Type *RetTy = F->getFunctionType()->getParamType(0);
760 RetTy = cast<PointerType>(RetTy)->getElementType();
761 Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
763 while (!F->use_empty()) {
764 CallInst *CI = cast<CallInst>(F->use_back());
765 Value *V = new CallInst(NF, "", CI);
766 new StoreInst(V, CI->getOperand(1), CI);
767 CI->getParent()->getInstList().erase(CI);
769 Result->getFunctionList().erase(F);
772 if (Function *F = Result->getNamedFunction("llvm.va_end")) {
773 assert(F->arg_size() == 1 && "Obsolete va_end takes 1 argument!");
774 const Type *ArgTy = F->getFunctionType()->getParamType(0);
775 ArgTy = cast<PointerType>(ArgTy)->getElementType();
776 Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
779 while (!F->use_empty()) {
780 CallInst *CI = cast<CallInst>(F->use_back());
781 Value *V = new LoadInst(CI->getOperand(1), "", CI);
782 new CallInst(NF, V, "", CI);
783 CI->getParent()->getInstList().erase(CI);
785 Result->getFunctionList().erase(F);
788 if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
789 assert(F->arg_size() == 2 && "Obsolete va_copy takes 2 argument!");
790 const Type *ArgTy = F->getFunctionType()->getParamType(0);
791 ArgTy = cast<PointerType>(ArgTy)->getElementType();
792 Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
795 while (!F->use_empty()) {
796 CallInst *CI = cast<CallInst>(F->use_back());
797 Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
798 new StoreInst(V, CI->getOperand(1), CI);
799 CI->getParent()->getInstList().erase(CI);
801 Result->getFunctionList().erase(F);
805 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
814 llvm::Module *ModuleVal;
815 llvm::Function *FunctionVal;
816 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
817 llvm::BasicBlock *BasicBlockVal;
818 llvm::TerminatorInst *TermInstVal;
819 llvm::Instruction *InstVal;
820 llvm::Constant *ConstVal;
822 const llvm::Type *PrimType;
823 llvm::PATypeHolder *TypeVal;
824 llvm::Value *ValueVal;
826 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
827 std::vector<llvm::Value*> *ValueList;
828 std::list<llvm::PATypeHolder> *TypeList;
829 std::list<std::pair<llvm::Value*,
830 llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
831 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
832 std::vector<llvm::Constant*> *ConstVector;
834 llvm::GlobalValue::LinkageTypes Linkage;
842 char *StrVal; // This memory is strdup'd!
843 llvm::ValID ValIDVal; // strdup'd memory maybe!
845 llvm::Instruction::BinaryOps BinaryOpVal;
846 llvm::Instruction::TermOps TermOpVal;
847 llvm::Instruction::MemoryOps MemOpVal;
848 llvm::Instruction::OtherOps OtherOpVal;
849 llvm::Module::Endianness Endianness;
852 %type <ModuleVal> Module FunctionList
853 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
854 %type <BasicBlockVal> BasicBlock InstructionList
855 %type <TermInstVal> BBTerminatorInst
856 %type <InstVal> Inst InstVal MemoryInst
857 %type <ConstVal> ConstVal ConstExpr
858 %type <ConstVector> ConstVector
859 %type <ArgList> ArgList ArgListH
860 %type <ArgVal> ArgVal
861 %type <PHIList> PHIList
862 %type <ValueList> ValueRefList ValueRefListE // For call param lists
863 %type <ValueList> IndexList // For GEP derived indices
864 %type <TypeList> TypeListI ArgTypeListI
865 %type <JumpTable> JumpTable
866 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
867 %type <BoolVal> OptVolatile // 'volatile' or not
868 %type <Linkage> OptLinkage
869 %type <Endianness> BigOrLittle
871 // ValueRef - Unresolved reference to a definition or BB
872 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
873 %type <ValueVal> ResolvedVal // <type> <valref> pair
874 // Tokens and types for handling constant integer values
876 // ESINT64VAL - A negative number within long long range
877 %token <SInt64Val> ESINT64VAL
879 // EUINT64VAL - A positive number within uns. long long range
880 %token <UInt64Val> EUINT64VAL
881 %type <SInt64Val> EINT64VAL
883 %token <SIntVal> SINTVAL // Signed 32 bit ints...
884 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
885 %type <SIntVal> INTVAL
886 %token <FPVal> FPVAL // Float or Double constant
889 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
890 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
891 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
892 %token <PrimType> FLOAT DOUBLE TYPE LABEL
894 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
895 %type <StrVal> Name OptName OptAssign
898 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
899 %token DECLARE GLOBAL CONSTANT VOLATILE
900 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
901 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG
904 // Basic Block Terminating Operators
905 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
908 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
909 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
910 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
912 // Memory Instructions
913 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
916 %type <OtherOpVal> ShiftOps
917 %token <OtherOpVal> PHI_TOK CALL CAST SELECT SHL SHR VAARG VANEXT
918 %token VA_ARG // FIXME: OBSOLETE
923 // Handle constant integer size restriction and conversion...
927 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
928 ThrowException("Value too large for type!");
933 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
934 EINT64VAL : EUINT64VAL {
935 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
936 ThrowException("Value too large for type!");
940 // Operations that are notably excluded from this list include:
941 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
943 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
944 LogicalOps : AND | OR | XOR;
945 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
947 ShiftOps : SHL | SHR;
949 // These are some types that allow classification if we only want a particular
950 // thing... for example, only a signed, unsigned, or integral type.
951 SIntType : LONG | INT | SHORT | SBYTE;
952 UIntType : ULONG | UINT | USHORT | UBYTE;
953 IntType : SIntType | UIntType;
954 FPType : FLOAT | DOUBLE;
956 // OptAssign - Value producing statements have an optional assignment component
957 OptAssign : Name '=' {
964 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
965 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
966 WEAK { $$ = GlobalValue::WeakLinkage; } |
967 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
968 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
970 //===----------------------------------------------------------------------===//
971 // Types includes all predefined types... except void, because it can only be
972 // used in specific contexts (function returning void for example). To have
973 // access to it, a user must explicitly use TypesV.
976 // TypesV includes all of 'Types', but it also includes the void type.
977 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
978 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
982 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
987 // Derived types are added later...
989 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
990 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
992 $$ = new PATypeHolder(OpaqueType::get());
995 $$ = new PATypeHolder($1);
997 UpRTypes : SymbolicValueRef { // Named types are also simple types...
998 $$ = new PATypeHolder(getTypeVal($1));
1001 // Include derived types in the Types production.
1003 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1004 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1005 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1006 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1007 $$ = new PATypeHolder(OT);
1008 UR_OUT("New Upreference!\n");
1010 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1011 std::vector<const Type*> Params;
1012 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1013 E = $3->end(); I != E; ++I)
1014 Params.push_back(*I);
1015 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1016 if (isVarArg) Params.pop_back();
1018 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1019 delete $3; // Delete the argument list
1020 delete $1; // Delete the return type handle
1022 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1023 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1026 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1027 const llvm::Type* ElemTy = $4->get();
1028 if ((unsigned)$2 != $2) {
1029 ThrowException("Unsigned result not equal to signed result");
1031 if(!ElemTy->isPrimitiveType()) {
1032 ThrowException("Elemental type of a PackedType must be primitive");
1034 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1037 | '{' TypeListI '}' { // Structure type?
1038 std::vector<const Type*> Elements;
1039 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1040 E = $2->end(); I != E; ++I)
1041 Elements.push_back(*I);
1043 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1046 | '{' '}' { // Empty structure type?
1047 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1049 | UpRTypes '*' { // Pointer type?
1050 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1054 // TypeList - Used for struct declarations and as a basis for function type
1055 // declaration type lists
1057 TypeListI : UpRTypes {
1058 $$ = new std::list<PATypeHolder>();
1059 $$->push_back(*$1); delete $1;
1061 | TypeListI ',' UpRTypes {
1062 ($$=$1)->push_back(*$3); delete $3;
1065 // ArgTypeList - List of types for a function type declaration...
1066 ArgTypeListI : TypeListI
1067 | TypeListI ',' DOTDOTDOT {
1068 ($$=$1)->push_back(Type::VoidTy);
1071 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1074 $$ = new std::list<PATypeHolder>();
1077 // ConstVal - The various declarations that go into the constant pool. This
1078 // production is used ONLY to represent constants that show up AFTER a 'const',
1079 // 'constant' or 'global' token at global scope. Constants that can be inlined
1080 // into other expressions (such as integers and constexprs) are handled by the
1081 // ResolvedVal, ValueRef and ConstValueRef productions.
1083 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1084 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1086 ThrowException("Cannot make array constant with type: '" +
1087 (*$1)->getDescription() + "'!");
1088 const Type *ETy = ATy->getElementType();
1089 int NumElements = ATy->getNumElements();
1091 // Verify that we have the correct size...
1092 if (NumElements != -1 && NumElements != (int)$3->size())
1093 ThrowException("Type mismatch: constant sized array 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 $$ = ConstantArray::get(ATy, *$3);
1106 delete $1; delete $3;
1109 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1111 ThrowException("Cannot make array constant with type: '" +
1112 (*$1)->getDescription() + "'!");
1114 int NumElements = ATy->getNumElements();
1115 if (NumElements != -1 && NumElements != 0)
1116 ThrowException("Type mismatch: constant sized array initialized with 0"
1117 " arguments, but has size of " + itostr(NumElements) +"!");
1118 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1121 | Types 'c' STRINGCONSTANT {
1122 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1124 ThrowException("Cannot make array constant with type: '" +
1125 (*$1)->getDescription() + "'!");
1127 int NumElements = ATy->getNumElements();
1128 const Type *ETy = ATy->getElementType();
1129 char *EndStr = UnEscapeLexed($3, true);
1130 if (NumElements != -1 && NumElements != (EndStr-$3))
1131 ThrowException("Can't build string constant of size " +
1132 itostr((int)(EndStr-$3)) +
1133 " when array has size " + itostr(NumElements) + "!");
1134 std::vector<Constant*> Vals;
1135 if (ETy == Type::SByteTy) {
1136 for (char *C = $3; C != EndStr; ++C)
1137 Vals.push_back(ConstantSInt::get(ETy, *C));
1138 } else if (ETy == Type::UByteTy) {
1139 for (char *C = $3; C != EndStr; ++C)
1140 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1143 ThrowException("Cannot build string arrays of non byte sized elements!");
1146 $$ = ConstantArray::get(ATy, Vals);
1149 | Types '<' ConstVector '>' { // Nonempty unsized arr
1150 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1152 ThrowException("Cannot make packed constant with type: '" +
1153 (*$1)->getDescription() + "'!");
1154 const Type *ETy = PTy->getElementType();
1155 int NumElements = PTy->getNumElements();
1157 // Verify that we have the correct size...
1158 if (NumElements != -1 && NumElements != (int)$3->size())
1159 ThrowException("Type mismatch: constant sized packed initialized with " +
1160 utostr($3->size()) + " arguments, but has size of " +
1161 itostr(NumElements) + "!");
1163 // Verify all elements are correct type!
1164 for (unsigned i = 0; i < $3->size(); i++) {
1165 if (ETy != (*$3)[i]->getType())
1166 ThrowException("Element #" + utostr(i) + " is not of type '" +
1167 ETy->getDescription() +"' as required!\nIt is of type '"+
1168 (*$3)[i]->getType()->getDescription() + "'.");
1171 $$ = ConstantPacked::get(PTy, *$3);
1172 delete $1; delete $3;
1174 | Types '{' ConstVector '}' {
1175 const StructType *STy = dyn_cast<StructType>($1->get());
1177 ThrowException("Cannot make struct constant with type: '" +
1178 (*$1)->getDescription() + "'!");
1180 if ($3->size() != STy->getNumContainedTypes())
1181 ThrowException("Illegal number of initializers for structure type!");
1183 // Check to ensure that constants are compatible with the type initializer!
1184 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1185 if ((*$3)[i]->getType() != STy->getElementType(i))
1186 ThrowException("Expected type '" +
1187 STy->getElementType(i)->getDescription() +
1188 "' for element #" + utostr(i) +
1189 " of structure initializer!");
1191 $$ = ConstantStruct::get(STy, *$3);
1192 delete $1; delete $3;
1195 const StructType *STy = dyn_cast<StructType>($1->get());
1197 ThrowException("Cannot make struct constant with type: '" +
1198 (*$1)->getDescription() + "'!");
1200 if (STy->getNumContainedTypes() != 0)
1201 ThrowException("Illegal number of initializers for structure type!");
1203 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1207 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1209 ThrowException("Cannot make null pointer constant with type: '" +
1210 (*$1)->getDescription() + "'!");
1212 $$ = ConstantPointerNull::get(PTy);
1216 $$ = UndefValue::get($1->get());
1219 | Types SymbolicValueRef {
1220 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1222 ThrowException("Global const reference must be a pointer type!");
1224 // ConstExprs can exist in the body of a function, thus creating
1225 // GlobalValues whenever they refer to a variable. Because we are in
1226 // the context of a function, getValNonImprovising will search the functions
1227 // symbol table instead of the module symbol table for the global symbol,
1228 // which throws things all off. To get around this, we just tell
1229 // getValNonImprovising that we are at global scope here.
1231 Function *SavedCurFn = CurFun.CurrentFunction;
1232 CurFun.CurrentFunction = 0;
1234 Value *V = getValNonImprovising(Ty, $2);
1236 CurFun.CurrentFunction = SavedCurFn;
1238 // If this is an initializer for a constant pointer, which is referencing a
1239 // (currently) undefined variable, create a stub now that shall be replaced
1240 // in the future with the right type of variable.
1243 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1244 const PointerType *PT = cast<PointerType>(Ty);
1246 // First check to see if the forward references value is already created!
1247 PerModuleInfo::GlobalRefsType::iterator I =
1248 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1250 if (I != CurModule.GlobalRefs.end()) {
1251 V = I->second; // Placeholder already exists, use it...
1255 if ($2.Type == ValID::NameVal) Name = $2.Name;
1257 // Create the forward referenced global.
1259 if (const FunctionType *FTy =
1260 dyn_cast<FunctionType>(PT->getElementType())) {
1261 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1262 CurModule.CurrentModule);
1264 GV = new GlobalVariable(PT->getElementType(), false,
1265 GlobalValue::ExternalLinkage, 0,
1266 Name, CurModule.CurrentModule);
1269 // Keep track of the fact that we have a forward ref to recycle it
1270 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1275 $$ = cast<GlobalValue>(V);
1276 delete $1; // Free the type handle
1279 if ($1->get() != $2->getType())
1280 ThrowException("Mismatched types for constant expression!");
1284 | Types ZEROINITIALIZER {
1285 const Type *Ty = $1->get();
1286 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1287 ThrowException("Cannot create a null initialized value of this type!");
1288 $$ = Constant::getNullValue(Ty);
1292 ConstVal : SIntType EINT64VAL { // integral constants
1293 if (!ConstantSInt::isValueValidForType($1, $2))
1294 ThrowException("Constant value doesn't fit in type!");
1295 $$ = ConstantSInt::get($1, $2);
1297 | UIntType EUINT64VAL { // integral constants
1298 if (!ConstantUInt::isValueValidForType($1, $2))
1299 ThrowException("Constant value doesn't fit in type!");
1300 $$ = ConstantUInt::get($1, $2);
1302 | BOOL TRUETOK { // Boolean constants
1303 $$ = ConstantBool::True;
1305 | BOOL FALSETOK { // Boolean constants
1306 $$ = ConstantBool::False;
1308 | FPType FPVAL { // Float & Double constants
1309 if (!ConstantFP::isValueValidForType($1, $2))
1310 ThrowException("Floating point constant invalid for type!!");
1311 $$ = ConstantFP::get($1, $2);
1315 ConstExpr: CAST '(' ConstVal TO Types ')' {
1316 if (!$3->getType()->isFirstClassType())
1317 ThrowException("cast constant expression from a non-primitive type: '" +
1318 $3->getType()->getDescription() + "'!");
1319 if (!$5->get()->isFirstClassType())
1320 ThrowException("cast constant expression to a non-primitive type: '" +
1321 $5->get()->getDescription() + "'!");
1322 $$ = ConstantExpr::getCast($3, $5->get());
1325 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1326 if (!isa<PointerType>($3->getType()))
1327 ThrowException("GetElementPtr requires a pointer operand!");
1329 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1330 // indices to uint struct indices for compatibility.
1331 generic_gep_type_iterator<std::vector<Value*>::iterator>
1332 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1333 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1334 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1335 if (isa<StructType>(*GTI)) // Only change struct indices
1336 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1337 if (CUI->getType() == Type::UByteTy)
1338 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1341 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1343 ThrowException("Index list invalid for constant getelementptr!");
1345 std::vector<Constant*> IdxVec;
1346 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1347 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1348 IdxVec.push_back(C);
1350 ThrowException("Indices to constant getelementptr must be constants!");
1354 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1356 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1357 if ($3->getType() != Type::BoolTy)
1358 ThrowException("Select condition must be of boolean type!");
1359 if ($5->getType() != $7->getType())
1360 ThrowException("Select operand types must match!");
1361 $$ = ConstantExpr::getSelect($3, $5, $7);
1363 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1364 if ($3->getType() != $5->getType())
1365 ThrowException("Binary operator types must match!");
1366 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1367 // To retain backward compatibility with these early compilers, we emit a
1368 // cast to the appropriate integer type automatically if we are in the
1369 // broken case. See PR424 for more information.
1370 if (!isa<PointerType>($3->getType())) {
1371 $$ = ConstantExpr::get($1, $3, $5);
1373 const Type *IntPtrTy = 0;
1374 switch (CurModule.CurrentModule->getPointerSize()) {
1375 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1376 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1377 default: ThrowException("invalid pointer binary constant expr!");
1379 $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1380 ConstantExpr::getCast($5, IntPtrTy));
1381 $$ = ConstantExpr::getCast($$, $3->getType());
1384 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1385 if ($3->getType() != $5->getType())
1386 ThrowException("Logical operator types must match!");
1387 if (!$3->getType()->isIntegral())
1388 ThrowException("Logical operands must have integral types!");
1389 $$ = ConstantExpr::get($1, $3, $5);
1391 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1392 if ($3->getType() != $5->getType())
1393 ThrowException("setcc operand types must match!");
1394 $$ = ConstantExpr::get($1, $3, $5);
1396 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1397 if ($5->getType() != Type::UByteTy)
1398 ThrowException("Shift count for shift constant must be unsigned byte!");
1399 if (!$3->getType()->isInteger())
1400 ThrowException("Shift constant expression requires integer operand!");
1401 $$ = ConstantExpr::get($1, $3, $5);
1405 // ConstVector - A list of comma separated constants.
1406 ConstVector : ConstVector ',' ConstVal {
1407 ($$ = $1)->push_back($3);
1410 $$ = new std::vector<Constant*>();
1415 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1416 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1419 //===----------------------------------------------------------------------===//
1420 // Rules to match Modules
1421 //===----------------------------------------------------------------------===//
1423 // Module rule: Capture the result of parsing the whole file into a result
1426 Module : FunctionList {
1427 $$ = ParserResult = $1;
1428 CurModule.ModuleDone();
1431 // FunctionList - A list of functions, preceeded by a constant pool.
1433 FunctionList : FunctionList Function {
1435 CurFun.FunctionDone();
1437 | FunctionList FunctionProto {
1440 | FunctionList IMPLEMENTATION {
1444 $$ = CurModule.CurrentModule;
1445 // Emit an error if there are any unresolved types left.
1446 if (!CurModule.LateResolveTypes.empty()) {
1447 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1448 if (DID.Type == ValID::NameVal)
1449 ThrowException("Reference to an undefined type: '"+DID.getName() + "'");
1451 ThrowException("Reference to an undefined type: #" + itostr(DID.Num));
1455 // ConstPool - Constants with optional names assigned to them.
1456 ConstPool : ConstPool OptAssign TYPE TypesV {
1457 // Eagerly resolve types. This is not an optimization, this is a
1458 // requirement that is due to the fact that we could have this:
1460 // %list = type { %list * }
1461 // %list = type { %list * } ; repeated type decl
1463 // If types are not resolved eagerly, then the two types will not be
1464 // determined to be the same type!
1466 ResolveTypeTo($2, *$4);
1468 if (!setTypeName(*$4, $2) && !$2) {
1469 // If this is a named type that is not a redefinition, add it to the slot
1471 CurModule.Types.push_back(*$4);
1476 | ConstPool FunctionProto { // Function prototypes can be in const pool
1478 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1479 if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1480 ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1482 | ConstPool OptAssign EXTERNAL GlobalType Types {
1483 ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1486 | ConstPool TARGET TargetDefinition {
1488 | ConstPool DEPLIBS '=' LibrariesDefinition {
1490 | /* empty: end of list */ {
1495 BigOrLittle : BIG { $$ = Module::BigEndian; };
1496 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1498 TargetDefinition : ENDIAN '=' BigOrLittle {
1499 CurModule.CurrentModule->setEndianness($3);
1501 | POINTERSIZE '=' EUINT64VAL {
1503 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1505 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1507 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1509 | TRIPLE '=' STRINGCONSTANT {
1510 CurModule.CurrentModule->setTargetTriple($3);
1514 LibrariesDefinition : '[' LibList ']';
1516 LibList : LibList ',' STRINGCONSTANT {
1517 CurModule.CurrentModule->addLibrary($3);
1521 CurModule.CurrentModule->addLibrary($1);
1524 | /* empty: end of list */ {
1528 //===----------------------------------------------------------------------===//
1529 // Rules to match Function Headers
1530 //===----------------------------------------------------------------------===//
1532 Name : VAR_ID | STRINGCONSTANT;
1533 OptName : Name | /*empty*/ { $$ = 0; };
1535 ArgVal : Types OptName {
1536 if (*$1 == Type::VoidTy)
1537 ThrowException("void typed arguments are invalid!");
1538 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1541 ArgListH : ArgListH ',' ArgVal {
1547 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1552 ArgList : ArgListH {
1555 | ArgListH ',' DOTDOTDOT {
1557 $$->push_back(std::pair<PATypeHolder*,
1558 char*>(new PATypeHolder(Type::VoidTy), 0));
1561 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1562 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1568 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1570 std::string FunctionName($2);
1571 free($2); // Free strdup'd memory!
1573 if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1574 ThrowException("LLVM functions cannot return aggregate types!");
1576 std::vector<const Type*> ParamTypeList;
1577 if ($4) { // If there are arguments...
1578 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1579 I != $4->end(); ++I)
1580 ParamTypeList.push_back(I->first->get());
1583 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1584 if (isVarArg) ParamTypeList.pop_back();
1586 const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1587 const PointerType *PFT = PointerType::get(FT);
1591 if (!FunctionName.empty()) {
1592 ID = ValID::create((char*)FunctionName.c_str());
1594 ID = ValID::create((int)CurModule.Values[PFT].size());
1598 // See if this function was forward referenced. If so, recycle the object.
1599 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1600 // Move the function to the end of the list, from whereever it was
1601 // previously inserted.
1602 Fn = cast<Function>(FWRef);
1603 CurModule.CurrentModule->getFunctionList().remove(Fn);
1604 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1605 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1606 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1607 // If this is the case, either we need to be a forward decl, or it needs
1609 if (!CurFun.isDeclare && !Fn->isExternal())
1610 ThrowException("Redefinition of function '" + FunctionName + "'!");
1612 // Make sure to strip off any argument names so we can't get conflicts.
1613 if (Fn->isExternal())
1614 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1618 } else { // Not already defined?
1619 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1620 CurModule.CurrentModule);
1621 InsertValue(Fn, CurModule.Values);
1624 CurFun.FunctionStart(Fn);
1626 // Add all of the arguments we parsed to the function...
1627 if ($4) { // Is null if empty...
1628 if (isVarArg) { // Nuke the last entry
1629 assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1630 "Not a varargs marker!");
1631 delete $4->back().first;
1632 $4->pop_back(); // Delete the last entry
1634 Function::arg_iterator ArgIt = Fn->arg_begin();
1635 for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1636 I != $4->end(); ++I, ++ArgIt) {
1637 delete I->first; // Delete the typeholder...
1639 setValueName(ArgIt, I->second); // Insert arg into symtab...
1643 delete $4; // We're now done with the argument list
1647 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1649 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1650 $$ = CurFun.CurrentFunction;
1652 // Make sure that we keep track of the linkage type even if there was a
1653 // previous "declare".
1657 END : ENDTOK | '}'; // Allow end of '}' to end a function
1659 Function : BasicBlockList END {
1663 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1664 $$ = CurFun.CurrentFunction;
1665 CurFun.FunctionDone();
1668 //===----------------------------------------------------------------------===//
1669 // Rules to match Basic Blocks
1670 //===----------------------------------------------------------------------===//
1672 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1673 $$ = ValID::create($1);
1676 $$ = ValID::create($1);
1678 | FPVAL { // Perhaps it's an FP constant?
1679 $$ = ValID::create($1);
1682 $$ = ValID::create(ConstantBool::True);
1685 $$ = ValID::create(ConstantBool::False);
1688 $$ = ValID::createNull();
1691 $$ = ValID::createUndef();
1693 | '<' ConstVector '>' { // Nonempty unsized packed vector
1694 const Type *ETy = (*$2)[0]->getType();
1695 int NumElements = $2->size();
1697 PackedType* pt = PackedType::get(ETy, NumElements);
1698 PATypeHolder* PTy = new PATypeHolder(
1706 // Verify all elements are correct type!
1707 for (unsigned i = 0; i < $2->size(); i++) {
1708 if (ETy != (*$2)[i]->getType())
1709 ThrowException("Element #" + utostr(i) + " is not of type '" +
1710 ETy->getDescription() +"' as required!\nIt is of type '" +
1711 (*$2)[i]->getType()->getDescription() + "'.");
1714 $$ = ValID::create(ConstantPacked::get(pt, *$2));
1715 delete PTy; delete $2;
1718 $$ = ValID::create($1);
1721 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1724 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1725 $$ = ValID::create($1);
1727 | Name { // Is it a named reference...?
1728 $$ = ValID::create($1);
1731 // ValueRef - A reference to a definition... either constant or symbolic
1732 ValueRef : SymbolicValueRef | ConstValueRef;
1735 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1736 // type immediately preceeds the value reference, and allows complex constant
1737 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1738 ResolvedVal : Types ValueRef {
1739 $$ = getVal(*$1, $2); delete $1;
1742 BasicBlockList : BasicBlockList BasicBlock {
1745 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1750 // Basic blocks are terminated by branching instructions:
1751 // br, br/cc, switch, ret
1753 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1754 setValueName($3, $2);
1757 $1->getInstList().push_back($3);
1762 InstructionList : InstructionList Inst {
1763 $1->getInstList().push_back($2);
1767 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1769 // Make sure to move the basic block to the correct location in the
1770 // function, instead of leaving it inserted wherever it was first
1772 CurFun.CurrentFunction->getBasicBlockList().remove(CurBB);
1773 CurFun.CurrentFunction->getBasicBlockList().push_back(CurBB);
1776 $$ = CurBB = getBBVal(ValID::create($1), true);
1778 // Make sure to move the basic block to the correct location in the
1779 // function, instead of leaving it inserted wherever it was first
1781 CurFun.CurrentFunction->getBasicBlockList().remove(CurBB);
1782 CurFun.CurrentFunction->getBasicBlockList().push_back(CurBB);
1785 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1786 $$ = new ReturnInst($2);
1788 | RET VOID { // Return with no result...
1789 $$ = new ReturnInst();
1791 | BR LABEL ValueRef { // Unconditional Branch...
1792 $$ = new BranchInst(getBBVal($3));
1793 } // Conditional Branch...
1794 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1795 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1797 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1798 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
1801 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1803 for (; I != E; ++I) {
1804 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
1805 S->addCase(CI, I->second);
1807 ThrowException("Switch case is constant, but not a simple integer!");
1811 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1812 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
1815 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO LABEL ValueRef
1816 UNWIND LABEL ValueRef {
1817 const PointerType *PFTy;
1818 const FunctionType *Ty;
1820 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1821 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1822 // Pull out the types of all of the arguments...
1823 std::vector<const Type*> ParamTypes;
1825 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1827 ParamTypes.push_back((*I)->getType());
1830 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1831 if (isVarArg) ParamTypes.pop_back();
1833 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1834 PFTy = PointerType::get(Ty);
1837 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1839 BasicBlock *Normal = getBBVal($9);
1840 BasicBlock *Except = getBBVal($12);
1842 // Create the call node...
1843 if (!$5) { // Has no arguments?
1844 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1845 } else { // Has arguments?
1846 // Loop through FunctionType's arguments and ensure they are specified
1849 FunctionType::param_iterator I = Ty->param_begin();
1850 FunctionType::param_iterator E = Ty->param_end();
1851 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1853 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1854 if ((*ArgI)->getType() != *I)
1855 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1856 (*I)->getDescription() + "'!");
1858 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1859 ThrowException("Invalid number of parameters detected!");
1861 $$ = new InvokeInst(V, Normal, Except, *$5);
1867 $$ = new UnwindInst();
1870 $$ = new UnreachableInst();
1875 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1877 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1879 ThrowException("May only switch on a constant pool value!");
1881 $$->push_back(std::make_pair(V, getBBVal($6)));
1883 | IntType ConstValueRef ',' LABEL ValueRef {
1884 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1885 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1888 ThrowException("May only switch on a constant pool value!");
1890 $$->push_back(std::make_pair(V, getBBVal($5)));
1893 Inst : OptAssign InstVal {
1894 // Is this definition named?? if so, assign the name...
1895 setValueName($2, $1);
1900 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1901 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1902 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
1905 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1907 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1912 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1913 $$ = new std::vector<Value*>();
1916 | ValueRefList ',' ResolvedVal {
1921 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1922 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1924 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1925 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
1926 !isa<PackedType>((*$2).get()))
1928 "Arithmetic operator requires integer, FP, or packed operands!");
1929 if(isa<PackedType>((*$2).get()) && $1 == Instruction::Rem) {
1931 "Rem not supported on packed types!");
1933 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1935 ThrowException("binary operator returned null!");
1938 | LogicalOps Types ValueRef ',' ValueRef {
1939 if (!(*$2)->isIntegral())
1940 ThrowException("Logical operator requires integral operands!");
1941 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1943 ThrowException("binary operator returned null!");
1946 | SetCondOps Types ValueRef ',' ValueRef {
1947 if(isa<PackedType>((*$2).get())) {
1949 "PackedTypes currently not supported in setcc instructions!");
1951 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1953 ThrowException("binary operator returned null!");
1957 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1958 << " Replacing with 'xor'.\n";
1960 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1962 ThrowException("Expected integral type for not instruction!");
1964 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1966 ThrowException("Could not create a xor instruction!");
1968 | ShiftOps ResolvedVal ',' ResolvedVal {
1969 if ($4->getType() != Type::UByteTy)
1970 ThrowException("Shift amount must be ubyte!");
1971 if (!$2->getType()->isInteger())
1972 ThrowException("Shift constant expression requires integer operand!");
1973 $$ = new ShiftInst($1, $2, $4);
1975 | CAST ResolvedVal TO Types {
1976 if (!$4->get()->isFirstClassType())
1977 ThrowException("cast instruction to a non-primitive type: '" +
1978 $4->get()->getDescription() + "'!");
1979 $$ = new CastInst($2, *$4);
1982 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1983 if ($2->getType() != Type::BoolTy)
1984 ThrowException("select condition must be boolean!");
1985 if ($4->getType() != $6->getType())
1986 ThrowException("select value types should match!");
1987 $$ = new SelectInst($2, $4, $6);
1989 | VA_ARG ResolvedVal ',' Types {
1990 // FIXME: This is emulation code for an obsolete syntax. This should be
1991 // removed at some point.
1992 if (!ObsoleteVarArgs) {
1993 std::cerr << "WARNING: this file uses obsolete features. "
1994 << "Assemble and disassemble to update it.\n";
1995 ObsoleteVarArgs = true;
1998 // First, load the valist...
1999 Instruction *CurVAList = new LoadInst($2, "");
2000 CurBB->getInstList().push_back(CurVAList);
2002 // Emit the vaarg instruction.
2003 $$ = new VAArgInst(CurVAList, *$4);
2005 // Now we must advance the pointer and update it in memory.
2006 Instruction *TheVANext = new VANextInst(CurVAList, *$4);
2007 CurBB->getInstList().push_back(TheVANext);
2009 CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
2012 | VAARG ResolvedVal ',' Types {
2013 $$ = new VAArgInst($2, *$4);
2016 | VANEXT ResolvedVal ',' Types {
2017 $$ = new VANextInst($2, *$4);
2021 const Type *Ty = $2->front().first->getType();
2022 if (!Ty->isFirstClassType())
2023 ThrowException("PHI node operands must be of first class type!");
2024 $$ = new PHINode(Ty);
2025 ((PHINode*)$$)->reserveOperandSpace($2->size());
2026 while ($2->begin() != $2->end()) {
2027 if ($2->front().first->getType() != Ty)
2028 ThrowException("All elements of a PHI node must be of the same type!");
2029 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2032 delete $2; // Free the list...
2034 | CALL TypesV ValueRef '(' ValueRefListE ')' {
2035 const PointerType *PFTy;
2036 const FunctionType *Ty;
2038 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
2039 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2040 // Pull out the types of all of the arguments...
2041 std::vector<const Type*> ParamTypes;
2043 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
2045 ParamTypes.push_back((*I)->getType());
2048 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2049 if (isVarArg) ParamTypes.pop_back();
2051 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
2052 ThrowException("LLVM functions cannot return aggregate types!");
2054 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
2055 PFTy = PointerType::get(Ty);
2058 Value *V = getVal(PFTy, $3); // Get the function we're calling...
2060 // Create the call node...
2061 if (!$5) { // Has no arguments?
2062 // Make sure no arguments is a good thing!
2063 if (Ty->getNumParams() != 0)
2064 ThrowException("No arguments passed to a function that "
2065 "expects arguments!");
2067 $$ = new CallInst(V, std::vector<Value*>());
2068 } else { // Has arguments?
2069 // Loop through FunctionType's arguments and ensure they are specified
2072 FunctionType::param_iterator I = Ty->param_begin();
2073 FunctionType::param_iterator E = Ty->param_end();
2074 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
2076 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2077 if ((*ArgI)->getType() != *I)
2078 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2079 (*I)->getDescription() + "'!");
2081 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2082 ThrowException("Invalid number of parameters detected!");
2084 $$ = new CallInst(V, *$5);
2094 // IndexList - List of indices for GEP based instructions...
2095 IndexList : ',' ValueRefList {
2098 $$ = new std::vector<Value*>();
2101 OptVolatile : VOLATILE {
2109 MemoryInst : MALLOC Types {
2110 $$ = new MallocInst(*$2);
2113 | MALLOC Types ',' UINT ValueRef {
2114 $$ = new MallocInst(*$2, getVal($4, $5));
2118 $$ = new AllocaInst(*$2);
2121 | ALLOCA Types ',' UINT ValueRef {
2122 $$ = new AllocaInst(*$2, getVal($4, $5));
2125 | FREE ResolvedVal {
2126 if (!isa<PointerType>($2->getType()))
2127 ThrowException("Trying to free nonpointer type " +
2128 $2->getType()->getDescription() + "!");
2129 $$ = new FreeInst($2);
2132 | OptVolatile LOAD Types ValueRef {
2133 if (!isa<PointerType>($3->get()))
2134 ThrowException("Can't load from nonpointer type: " +
2135 (*$3)->getDescription());
2136 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2137 ThrowException("Can't load from pointer of non-first-class type: " +
2138 (*$3)->getDescription());
2139 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2142 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2143 const PointerType *PT = dyn_cast<PointerType>($5->get());
2145 ThrowException("Can't store to a nonpointer type: " +
2146 (*$5)->getDescription());
2147 const Type *ElTy = PT->getElementType();
2148 if (ElTy != $3->getType())
2149 ThrowException("Can't store '" + $3->getType()->getDescription() +
2150 "' into space of type '" + ElTy->getDescription() + "'!");
2152 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2155 | GETELEMENTPTR Types ValueRef IndexList {
2156 if (!isa<PointerType>($2->get()))
2157 ThrowException("getelementptr insn requires pointer operand!");
2159 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2160 // indices to uint struct indices for compatibility.
2161 generic_gep_type_iterator<std::vector<Value*>::iterator>
2162 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2163 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2164 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2165 if (isa<StructType>(*GTI)) // Only change struct indices
2166 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2167 if (CUI->getType() == Type::UByteTy)
2168 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2170 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2171 ThrowException("Invalid getelementptr indices for type '" +
2172 (*$2)->getDescription()+ "'!");
2173 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2174 delete $2; delete $4;
2179 int yyerror(const char *ErrorMsg) {
2181 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2182 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2183 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2184 if (yychar == YYEMPTY || yychar == 0)
2185 errMsg += "end-of-file.";
2187 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2188 ThrowException(errMsg);