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 std::vector<PATypeHolder> Types;
134 std::map<ValID, PATypeHolder> LateResolveTypes;
135 bool isDeclare; // Is this function a forward declararation?
137 /// BBForwardRefs - When we see forward references to basic blocks, keep
138 /// track of them here.
139 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
140 std::vector<BasicBlock*> NumberedBlocks;
143 inline PerFunctionInfo() {
148 inline void FunctionStart(Function *M) {
153 void FunctionDone() {
154 NumberedBlocks.clear();
156 // Any forward referenced blocks left?
157 if (!BBForwardRefs.empty())
158 ThrowException("Undefined reference to label " +
159 BBForwardRefs.begin()->second.first.getName());
161 // Resolve all forward references now.
162 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
164 Values.clear(); // Clear out function local definitions
165 Types.clear(); // Clear out function local types
169 } CurFun; // Info for the current function...
171 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
174 //===----------------------------------------------------------------------===//
175 // Code to handle definitions of all the types
176 //===----------------------------------------------------------------------===//
178 static int InsertValue(Value *V,
179 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
180 if (V->hasName()) return -1; // Is this a numbered definition?
182 // Yes, insert the value into the value table...
183 ValueList &List = ValueTab[V->getType()];
185 return List.size()-1;
188 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
190 case ValID::NumberVal: // Is it a numbered definition?
191 // Module constants occupy the lowest numbered slots...
192 if ((unsigned)D.Num < CurModule.Types.size())
193 return CurModule.Types[(unsigned)D.Num];
195 case ValID::NameVal: // Is it a named definition?
196 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
197 D.destroy(); // Free old strdup'd memory...
202 ThrowException("Internal parser error: Invalid symbol type reference!");
205 // If we reached here, we referenced either a symbol that we don't know about
206 // or an id number that hasn't been read yet. We may be referencing something
207 // forward, so just create an entry to be resolved later and get to it...
209 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
211 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
212 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
214 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
215 if (I != LateResolver.end()) {
219 Type *Typ = OpaqueType::get();
220 LateResolver.insert(std::make_pair(D, Typ));
224 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
225 SymbolTable &SymTab =
226 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
227 CurModule.CurrentModule->getSymbolTable();
228 return SymTab.lookup(Ty, Name);
231 // getValNonImprovising - Look up the value specified by the provided type and
232 // the provided ValID. If the value exists and has already been defined, return
233 // it. Otherwise return null.
235 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
236 if (isa<FunctionType>(Ty))
237 ThrowException("Functions are not values and "
238 "must be referenced as pointers");
241 case ValID::NumberVal: { // Is it a numbered definition?
242 unsigned Num = (unsigned)D.Num;
244 // Module constants occupy the lowest numbered slots...
245 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
246 if (VI != CurModule.Values.end()) {
247 if (Num < VI->second.size())
248 return VI->second[Num];
249 Num -= VI->second.size();
252 // Make sure that our type is within bounds
253 VI = CurFun.Values.find(Ty);
254 if (VI == CurFun.Values.end()) return 0;
256 // Check that the number is within bounds...
257 if (VI->second.size() <= Num) return 0;
259 return VI->second[Num];
262 case ValID::NameVal: { // Is it a named definition?
263 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
264 if (N == 0) return 0;
266 D.destroy(); // Free old strdup'd memory...
270 // Check to make sure that "Ty" is an integral type, and that our
271 // value will fit into the specified type...
272 case ValID::ConstSIntVal: // Is it a constant pool reference??
273 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
274 ThrowException("Signed integral constant '" +
275 itostr(D.ConstPool64) + "' is invalid for type '" +
276 Ty->getDescription() + "'!");
277 return ConstantSInt::get(Ty, D.ConstPool64);
279 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
280 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
281 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
282 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
283 "' is invalid or out of range!");
284 } else { // This is really a signed reference. Transmogrify.
285 return ConstantSInt::get(Ty, D.ConstPool64);
288 return ConstantUInt::get(Ty, D.UConstPool64);
291 case ValID::ConstFPVal: // Is it a floating point const pool reference?
292 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
293 ThrowException("FP constant invalid for type!!");
294 return ConstantFP::get(Ty, D.ConstPoolFP);
296 case ValID::ConstNullVal: // Is it a null value?
297 if (!isa<PointerType>(Ty))
298 ThrowException("Cannot create a a non pointer null!");
299 return ConstantPointerNull::get(cast<PointerType>(Ty));
301 case ValID::ConstUndefVal: // Is it an undef value?
302 return UndefValue::get(Ty);
304 case ValID::ConstantVal: // Fully resolved constant?
305 if (D.ConstantValue->getType() != Ty)
306 ThrowException("Constant expression type different from required type!");
307 return D.ConstantValue;
310 assert(0 && "Unhandled case!");
314 assert(0 && "Unhandled case!");
318 // getVal - This function is identical to getValNonImprovising, except that if a
319 // value is not already defined, it "improvises" by creating a placeholder var
320 // that looks and acts just like the requested variable. When the value is
321 // defined later, all uses of the placeholder variable are replaced with the
324 static Value *getVal(const Type *Ty, const ValID &ID) {
325 if (Ty == Type::LabelTy)
326 ThrowException("Cannot use a basic block here");
328 // See if the value has already been defined.
329 Value *V = getValNonImprovising(Ty, ID);
332 // If we reached here, we referenced either a symbol that we don't know about
333 // or an id number that hasn't been read yet. We may be referencing something
334 // forward, so just create an entry to be resolved later and get to it...
336 V = new Argument(Ty);
338 // Remember where this forward reference came from. FIXME, shouldn't we try
339 // to recycle these things??
340 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
343 if (inFunctionScope())
344 InsertValue(V, CurFun.LateResolveValues);
346 InsertValue(V, CurModule.LateResolveValues);
350 /// getBBVal - This is used for two purposes:
351 /// * If isDefinition is true, a new basic block with the specified ID is being
353 /// * If isDefinition is true, this is a reference to a basic block, which may
354 /// or may not be a forward reference.
356 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
357 assert(inFunctionScope() && "Can't get basic block at global scope!");
362 default: ThrowException("Illegal label reference " + ID.getName());
363 case ValID::NumberVal: // Is it a numbered definition?
364 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
365 CurFun.NumberedBlocks.resize(ID.Num+1);
366 BB = CurFun.NumberedBlocks[ID.Num];
368 case ValID::NameVal: // Is it a named definition?
370 if (Value *N = CurFun.CurrentFunction->
371 getSymbolTable().lookup(Type::LabelTy, Name))
372 BB = cast<BasicBlock>(N);
376 // See if the block has already been defined.
378 // If this is the definition of the block, make sure the existing value was
379 // just a forward reference. If it was a forward reference, there will be
380 // an entry for it in the PlaceHolderInfo map.
381 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
382 // The existing value was a definition, not a forward reference.
383 ThrowException("Redefinition of label " + ID.getName());
385 ID.destroy(); // Free strdup'd memory.
389 // Otherwise this block has not been seen before.
390 BB = new BasicBlock("", CurFun.CurrentFunction);
391 if (ID.Type == ValID::NameVal) {
392 BB->setName(ID.Name);
394 CurFun.NumberedBlocks[ID.Num] = BB;
397 // If this is not a definition, keep track of it so we can use it as a forward
400 // Remember where this forward reference came from.
401 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
403 // The forward declaration could have been inserted anywhere in the
404 // function: insert it into the correct place now.
405 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
406 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
413 //===----------------------------------------------------------------------===//
414 // Code to handle forward references in instructions
415 //===----------------------------------------------------------------------===//
417 // This code handles the late binding needed with statements that reference
418 // values not defined yet... for example, a forward branch, or the PHI node for
421 // This keeps a table (CurFun.LateResolveValues) of all such forward references
422 // and back patchs after we are done.
425 // ResolveDefinitions - If we could not resolve some defs at parsing
426 // time (forward branches, phi functions for loops, etc...) resolve the
429 static void ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
430 std::map<const Type*,ValueList> *FutureLateResolvers) {
431 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
432 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
433 E = LateResolvers.end(); LRI != E; ++LRI) {
434 ValueList &List = LRI->second;
435 while (!List.empty()) {
436 Value *V = List.back();
439 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
440 CurModule.PlaceHolderInfo.find(V);
441 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
443 ValID &DID = PHI->second.first;
445 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
447 V->replaceAllUsesWith(TheRealValue);
449 CurModule.PlaceHolderInfo.erase(PHI);
450 } else if (FutureLateResolvers) {
451 // Functions have their unresolved items forwarded to the module late
453 InsertValue(V, *FutureLateResolvers);
455 if (DID.Type == ValID::NameVal)
456 ThrowException("Reference to an invalid definition: '" +DID.getName()+
457 "' of type '" + V->getType()->getDescription() + "'",
460 ThrowException("Reference to an invalid definition: #" +
461 itostr(DID.Num) + " of type '" +
462 V->getType()->getDescription() + "'",
468 LateResolvers.clear();
471 // ResolveTypeTo - A brand new type was just declared. This means that (if
472 // name is not null) things referencing Name can be resolved. Otherwise, things
473 // refering to the number can be resolved. Do this now.
475 static void ResolveTypeTo(char *Name, const Type *ToTy) {
476 std::vector<PATypeHolder> &Types = inFunctionScope() ?
477 CurFun.Types : CurModule.Types;
480 if (Name) D = ValID::create(Name);
481 else D = ValID::create((int)Types.size());
483 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
484 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
486 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
487 if (I != LateResolver.end()) {
488 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
489 LateResolver.erase(I);
493 // ResolveTypes - At this point, all types should be resolved. Any that aren't
496 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
497 if (!LateResolveTypes.empty()) {
498 const ValID &DID = LateResolveTypes.begin()->first;
500 if (DID.Type == ValID::NameVal)
501 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
503 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
507 // setValueName - Set the specified value to the name given. The name may be
508 // null potentially, in which case this is a noop. The string passed in is
509 // assumed to be a malloc'd string buffer, and is free'd by this function.
511 static void setValueName(Value *V, char *NameStr) {
513 std::string Name(NameStr); // Copy string
514 free(NameStr); // Free old string
516 if (V->getType() == Type::VoidTy)
517 ThrowException("Can't assign name '" + Name+"' to value with void type!");
519 assert(inFunctionScope() && "Must be in function scope!");
520 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
521 if (ST.lookup(V->getType(), Name))
522 ThrowException("Redefinition of value named '" + Name + "' in the '" +
523 V->getType()->getDescription() + "' type plane!");
526 V->setName(Name, &ST);
530 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
531 /// this is a declaration, otherwise it is a definition.
532 static void ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
533 bool isConstantGlobal, const Type *Ty,
534 Constant *Initializer) {
535 if (isa<FunctionType>(Ty))
536 ThrowException("Cannot declare global vars of function type!");
538 const PointerType *PTy = PointerType::get(Ty);
542 Name = NameStr; // Copy string
543 free(NameStr); // Free old string
546 // See if this global value was forward referenced. If so, recycle the
550 ID = ValID::create((char*)Name.c_str());
552 ID = ValID::create((int)CurModule.Values[PTy].size());
555 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
556 // Move the global to the end of the list, from whereever it was
557 // previously inserted.
558 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
559 CurModule.CurrentModule->getGlobalList().remove(GV);
560 CurModule.CurrentModule->getGlobalList().push_back(GV);
561 GV->setInitializer(Initializer);
562 GV->setLinkage(Linkage);
563 GV->setConstant(isConstantGlobal);
564 InsertValue(GV, CurModule.Values);
568 // If this global has a name, check to see if there is already a definition
569 // of this global in the module. If so, merge as appropriate. Note that
570 // this is really just a hack around problems in the CFE. :(
572 // We are a simple redefinition of a value, check to see if it is defined
573 // the same as the old one.
574 if (GlobalVariable *EGV =
575 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
576 // We are allowed to redefine a global variable in two circumstances:
577 // 1. If at least one of the globals is uninitialized or
578 // 2. If both initializers have the same value.
580 if (!EGV->hasInitializer() || !Initializer ||
581 EGV->getInitializer() == Initializer) {
583 // Make sure the existing global version gets the initializer! Make
584 // sure that it also gets marked const if the new version is.
585 if (Initializer && !EGV->hasInitializer())
586 EGV->setInitializer(Initializer);
587 if (isConstantGlobal)
588 EGV->setConstant(true);
589 EGV->setLinkage(Linkage);
593 ThrowException("Redefinition of global variable named '" + Name +
594 "' in the '" + Ty->getDescription() + "' type plane!");
598 // Otherwise there is no existing GV to use, create one now.
600 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
601 CurModule.CurrentModule);
602 InsertValue(GV, CurModule.Values);
605 // setTypeName - Set the specified type to the name given. The name may be
606 // null potentially, in which case this is a noop. The string passed in is
607 // assumed to be a malloc'd string buffer, and is freed by this function.
609 // This function returns true if the type has already been defined, but is
610 // allowed to be redefined in the specified context. If the name is a new name
611 // for the type plane, it is inserted and false is returned.
612 static bool setTypeName(const Type *T, char *NameStr) {
613 assert(!inFunctionScope() && "Can't give types function-local names!");
614 if (NameStr == 0) return false;
616 std::string Name(NameStr); // Copy string
617 free(NameStr); // Free old string
619 // We don't allow assigning names to void type
620 if (T == Type::VoidTy)
621 ThrowException("Can't assign name '" + Name + "' to the void type!");
623 // Set the type name, checking for conflicts as we do so.
624 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
626 if (AlreadyExists) { // Inserting a name that is already defined???
627 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
628 assert(Existing && "Conflict but no matching type?");
630 // There is only one case where this is allowed: when we are refining an
631 // opaque type. In this case, Existing will be an opaque type.
632 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
633 // We ARE replacing an opaque type!
634 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
638 // Otherwise, this is an attempt to redefine a type. That's okay if
639 // the redefinition is identical to the original. This will be so if
640 // Existing and T point to the same Type object. In this one case we
641 // allow the equivalent redefinition.
642 if (Existing == T) return true; // Yes, it's equal.
644 // Any other kind of (non-equivalent) redefinition is an error.
645 ThrowException("Redefinition of type named '" + Name + "' in the '" +
646 T->getDescription() + "' type plane!");
652 //===----------------------------------------------------------------------===//
653 // Code for handling upreferences in type names...
656 // TypeContains - Returns true if Ty directly contains E in it.
658 static bool TypeContains(const Type *Ty, const Type *E) {
659 return find(Ty->subtype_begin(), Ty->subtype_end(), E) != Ty->subtype_end();
664 // NestingLevel - The number of nesting levels that need to be popped before
665 // this type is resolved.
666 unsigned NestingLevel;
668 // LastContainedTy - This is the type at the current binding level for the
669 // type. Every time we reduce the nesting level, this gets updated.
670 const Type *LastContainedTy;
672 // UpRefTy - This is the actual opaque type that the upreference is
676 UpRefRecord(unsigned NL, OpaqueType *URTy)
677 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
681 // UpRefs - A list of the outstanding upreferences that need to be resolved.
682 static std::vector<UpRefRecord> UpRefs;
684 /// HandleUpRefs - Every time we finish a new layer of types, this function is
685 /// called. It loops through the UpRefs vector, which is a list of the
686 /// currently active types. For each type, if the up reference is contained in
687 /// the newly completed type, we decrement the level count. When the level
688 /// count reaches zero, the upreferenced type is the type that is passed in:
689 /// thus we can complete the cycle.
691 static PATypeHolder HandleUpRefs(const Type *ty) {
692 if (!ty->isAbstract()) return ty;
694 UR_OUT("Type '" << Ty->getDescription() <<
695 "' newly formed. Resolving upreferences.\n" <<
696 UpRefs.size() << " upreferences active!\n");
698 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
699 // to zero), we resolve them all together before we resolve them to Ty. At
700 // the end of the loop, if there is anything to resolve to Ty, it will be in
702 OpaqueType *TypeToResolve = 0;
704 for (unsigned i = 0; i != UpRefs.size(); ++i) {
705 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
706 << UpRefs[i].second->getDescription() << ") = "
707 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
708 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
709 // Decrement level of upreference
710 unsigned Level = --UpRefs[i].NestingLevel;
711 UpRefs[i].LastContainedTy = Ty;
712 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
713 if (Level == 0) { // Upreference should be resolved!
714 if (!TypeToResolve) {
715 TypeToResolve = UpRefs[i].UpRefTy;
717 UR_OUT(" * Resolving upreference for "
718 << UpRefs[i].second->getDescription() << "\n";
719 std::string OldName = UpRefs[i].UpRefTy->getDescription());
720 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
721 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
722 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
724 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
725 --i; // Do not skip the next element...
731 UR_OUT(" * Resolving upreference for "
732 << UpRefs[i].second->getDescription() << "\n";
733 std::string OldName = TypeToResolve->getDescription());
734 TypeToResolve->refineAbstractTypeTo(Ty);
741 //===----------------------------------------------------------------------===//
742 // RunVMAsmParser - Define an interface to this parser
743 //===----------------------------------------------------------------------===//
745 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
747 CurFilename = Filename;
748 llvmAsmlineno = 1; // Reset the current line number...
749 ObsoleteVarArgs = false;
751 // Allocate a new module to read
752 CurModule.CurrentModule = new Module(Filename);
754 yyparse(); // Parse the file, potentially throwing exception
756 Module *Result = ParserResult;
758 // Check to see if they called va_start but not va_arg..
759 if (!ObsoleteVarArgs)
760 if (Function *F = Result->getNamedFunction("llvm.va_start"))
761 if (F->asize() == 1) {
762 std::cerr << "WARNING: this file uses obsolete features. "
763 << "Assemble and disassemble to update it.\n";
764 ObsoleteVarArgs = true;
767 if (ObsoleteVarArgs) {
768 // If the user is making use of obsolete varargs intrinsics, adjust them for
770 if (Function *F = Result->getNamedFunction("llvm.va_start")) {
771 assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
773 const Type *RetTy = F->getFunctionType()->getParamType(0);
774 RetTy = cast<PointerType>(RetTy)->getElementType();
775 Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
777 while (!F->use_empty()) {
778 CallInst *CI = cast<CallInst>(F->use_back());
779 Value *V = new CallInst(NF, "", CI);
780 new StoreInst(V, CI->getOperand(1), CI);
781 CI->getParent()->getInstList().erase(CI);
783 Result->getFunctionList().erase(F);
786 if (Function *F = Result->getNamedFunction("llvm.va_end")) {
787 assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
788 const Type *ArgTy = F->getFunctionType()->getParamType(0);
789 ArgTy = cast<PointerType>(ArgTy)->getElementType();
790 Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
793 while (!F->use_empty()) {
794 CallInst *CI = cast<CallInst>(F->use_back());
795 Value *V = new LoadInst(CI->getOperand(1), "", CI);
796 new CallInst(NF, V, "", CI);
797 CI->getParent()->getInstList().erase(CI);
799 Result->getFunctionList().erase(F);
802 if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
803 assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
804 const Type *ArgTy = F->getFunctionType()->getParamType(0);
805 ArgTy = cast<PointerType>(ArgTy)->getElementType();
806 Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
809 while (!F->use_empty()) {
810 CallInst *CI = cast<CallInst>(F->use_back());
811 Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
812 new StoreInst(V, CI->getOperand(1), CI);
813 CI->getParent()->getInstList().erase(CI);
815 Result->getFunctionList().erase(F);
819 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
828 llvm::Module *ModuleVal;
829 llvm::Function *FunctionVal;
830 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
831 llvm::BasicBlock *BasicBlockVal;
832 llvm::TerminatorInst *TermInstVal;
833 llvm::Instruction *InstVal;
834 llvm::Constant *ConstVal;
836 const llvm::Type *PrimType;
837 llvm::PATypeHolder *TypeVal;
838 llvm::Value *ValueVal;
840 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
841 std::vector<llvm::Value*> *ValueList;
842 std::list<llvm::PATypeHolder> *TypeList;
843 std::list<std::pair<llvm::Value*,
844 llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
845 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
846 std::vector<llvm::Constant*> *ConstVector;
848 llvm::GlobalValue::LinkageTypes Linkage;
856 char *StrVal; // This memory is strdup'd!
857 llvm::ValID ValIDVal; // strdup'd memory maybe!
859 llvm::Instruction::BinaryOps BinaryOpVal;
860 llvm::Instruction::TermOps TermOpVal;
861 llvm::Instruction::MemoryOps MemOpVal;
862 llvm::Instruction::OtherOps OtherOpVal;
863 llvm::Module::Endianness Endianness;
866 %type <ModuleVal> Module FunctionList
867 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
868 %type <BasicBlockVal> BasicBlock InstructionList
869 %type <TermInstVal> BBTerminatorInst
870 %type <InstVal> Inst InstVal MemoryInst
871 %type <ConstVal> ConstVal ConstExpr
872 %type <ConstVector> ConstVector
873 %type <ArgList> ArgList ArgListH
874 %type <ArgVal> ArgVal
875 %type <PHIList> PHIList
876 %type <ValueList> ValueRefList ValueRefListE // For call param lists
877 %type <ValueList> IndexList // For GEP derived indices
878 %type <TypeList> TypeListI ArgTypeListI
879 %type <JumpTable> JumpTable
880 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
881 %type <BoolVal> OptVolatile // 'volatile' or not
882 %type <Linkage> OptLinkage
883 %type <Endianness> BigOrLittle
885 // ValueRef - Unresolved reference to a definition or BB
886 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
887 %type <ValueVal> ResolvedVal // <type> <valref> pair
888 // Tokens and types for handling constant integer values
890 // ESINT64VAL - A negative number within long long range
891 %token <SInt64Val> ESINT64VAL
893 // EUINT64VAL - A positive number within uns. long long range
894 %token <UInt64Val> EUINT64VAL
895 %type <SInt64Val> EINT64VAL
897 %token <SIntVal> SINTVAL // Signed 32 bit ints...
898 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
899 %type <SIntVal> INTVAL
900 %token <FPVal> FPVAL // Float or Double constant
903 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
904 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
905 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
906 %token <PrimType> FLOAT DOUBLE TYPE LABEL
908 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
909 %type <StrVal> Name OptName OptAssign
912 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
913 %token DECLARE GLOBAL CONSTANT VOLATILE
914 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
915 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG
918 // Basic Block Terminating Operators
919 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
922 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
923 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
924 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
926 // Memory Instructions
927 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
930 %type <OtherOpVal> ShiftOps
931 %token <OtherOpVal> PHI_TOK CALL CAST SELECT SHL SHR VAARG VANEXT
932 %token VA_ARG // FIXME: OBSOLETE
937 // Handle constant integer size restriction and conversion...
941 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
942 ThrowException("Value too large for type!");
947 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
948 EINT64VAL : EUINT64VAL {
949 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
950 ThrowException("Value too large for type!");
954 // Operations that are notably excluded from this list include:
955 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
957 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
958 LogicalOps : AND | OR | XOR;
959 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
961 ShiftOps : SHL | SHR;
963 // These are some types that allow classification if we only want a particular
964 // thing... for example, only a signed, unsigned, or integral type.
965 SIntType : LONG | INT | SHORT | SBYTE;
966 UIntType : ULONG | UINT | USHORT | UBYTE;
967 IntType : SIntType | UIntType;
968 FPType : FLOAT | DOUBLE;
970 // OptAssign - Value producing statements have an optional assignment component
971 OptAssign : Name '=' {
978 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
979 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
980 WEAK { $$ = GlobalValue::WeakLinkage; } |
981 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
982 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
984 //===----------------------------------------------------------------------===//
985 // Types includes all predefined types... except void, because it can only be
986 // used in specific contexts (function returning void for example). To have
987 // access to it, a user must explicitly use TypesV.
990 // TypesV includes all of 'Types', but it also includes the void type.
991 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
992 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
996 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
1001 // Derived types are added later...
1003 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1004 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1006 $$ = new PATypeHolder(OpaqueType::get());
1009 $$ = new PATypeHolder($1);
1011 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1012 $$ = new PATypeHolder(getTypeVal($1));
1015 // Include derived types in the Types production.
1017 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1018 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1019 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1020 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1021 $$ = new PATypeHolder(OT);
1022 UR_OUT("New Upreference!\n");
1024 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1025 std::vector<const Type*> Params;
1026 mapto($3->begin(), $3->end(), std::back_inserter(Params),
1027 std::mem_fun_ref(&PATypeHolder::get));
1028 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1029 if (isVarArg) Params.pop_back();
1031 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1032 delete $3; // Delete the argument list
1033 delete $1; // Delete the return type handle
1035 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1036 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1039 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1040 const llvm::Type* ElemTy = $4->get();
1041 if ((unsigned)$2 != $2) {
1042 ThrowException("Unsigned result not equal to signed result");
1044 if(!ElemTy->isPrimitiveType()) {
1045 ThrowException("Elemental type of a PackedType must be primitive");
1047 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1050 | '{' TypeListI '}' { // Structure type?
1051 std::vector<const Type*> Elements;
1052 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
1053 std::mem_fun_ref(&PATypeHolder::get));
1055 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1058 | '{' '}' { // Empty structure type?
1059 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1061 | UpRTypes '*' { // Pointer type?
1062 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1066 // TypeList - Used for struct declarations and as a basis for function type
1067 // declaration type lists
1069 TypeListI : UpRTypes {
1070 $$ = new std::list<PATypeHolder>();
1071 $$->push_back(*$1); delete $1;
1073 | TypeListI ',' UpRTypes {
1074 ($$=$1)->push_back(*$3); delete $3;
1077 // ArgTypeList - List of types for a function type declaration...
1078 ArgTypeListI : TypeListI
1079 | TypeListI ',' DOTDOTDOT {
1080 ($$=$1)->push_back(Type::VoidTy);
1083 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1086 $$ = new std::list<PATypeHolder>();
1089 // ConstVal - The various declarations that go into the constant pool. This
1090 // production is used ONLY to represent constants that show up AFTER a 'const',
1091 // 'constant' or 'global' token at global scope. Constants that can be inlined
1092 // into other expressions (such as integers and constexprs) are handled by the
1093 // ResolvedVal, ValueRef and ConstValueRef productions.
1095 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1096 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1098 ThrowException("Cannot make array constant with type: '" +
1099 (*$1)->getDescription() + "'!");
1100 const Type *ETy = ATy->getElementType();
1101 int NumElements = ATy->getNumElements();
1103 // Verify that we have the correct size...
1104 if (NumElements != -1 && NumElements != (int)$3->size())
1105 ThrowException("Type mismatch: constant sized array initialized with " +
1106 utostr($3->size()) + " arguments, but has size of " +
1107 itostr(NumElements) + "!");
1109 // Verify all elements are correct type!
1110 for (unsigned i = 0; i < $3->size(); i++) {
1111 if (ETy != (*$3)[i]->getType())
1112 ThrowException("Element #" + utostr(i) + " is not of type '" +
1113 ETy->getDescription() +"' as required!\nIt is of type '"+
1114 (*$3)[i]->getType()->getDescription() + "'.");
1117 $$ = ConstantArray::get(ATy, *$3);
1118 delete $1; delete $3;
1121 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1123 ThrowException("Cannot make array constant with type: '" +
1124 (*$1)->getDescription() + "'!");
1126 int NumElements = ATy->getNumElements();
1127 if (NumElements != -1 && NumElements != 0)
1128 ThrowException("Type mismatch: constant sized array initialized with 0"
1129 " arguments, but has size of " + itostr(NumElements) +"!");
1130 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1133 | Types 'c' STRINGCONSTANT {
1134 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1136 ThrowException("Cannot make array constant with type: '" +
1137 (*$1)->getDescription() + "'!");
1139 int NumElements = ATy->getNumElements();
1140 const Type *ETy = ATy->getElementType();
1141 char *EndStr = UnEscapeLexed($3, true);
1142 if (NumElements != -1 && NumElements != (EndStr-$3))
1143 ThrowException("Can't build string constant of size " +
1144 itostr((int)(EndStr-$3)) +
1145 " when array has size " + itostr(NumElements) + "!");
1146 std::vector<Constant*> Vals;
1147 if (ETy == Type::SByteTy) {
1148 for (char *C = $3; C != EndStr; ++C)
1149 Vals.push_back(ConstantSInt::get(ETy, *C));
1150 } else if (ETy == Type::UByteTy) {
1151 for (char *C = $3; C != EndStr; ++C)
1152 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1155 ThrowException("Cannot build string arrays of non byte sized elements!");
1158 $$ = ConstantArray::get(ATy, Vals);
1161 | Types '<' ConstVector '>' { // Nonempty unsized arr
1162 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1164 ThrowException("Cannot make packed constant with type: '" +
1165 (*$1)->getDescription() + "'!");
1166 const Type *ETy = PTy->getElementType();
1167 int NumElements = PTy->getNumElements();
1169 // Verify that we have the correct size...
1170 if (NumElements != -1 && NumElements != (int)$3->size())
1171 ThrowException("Type mismatch: constant sized packed initialized with " +
1172 utostr($3->size()) + " arguments, but has size of " +
1173 itostr(NumElements) + "!");
1175 // Verify all elements are correct type!
1176 for (unsigned i = 0; i < $3->size(); i++) {
1177 if (ETy != (*$3)[i]->getType())
1178 ThrowException("Element #" + utostr(i) + " is not of type '" +
1179 ETy->getDescription() +"' as required!\nIt is of type '"+
1180 (*$3)[i]->getType()->getDescription() + "'.");
1183 $$ = ConstantPacked::get(PTy, *$3);
1184 delete $1; delete $3;
1186 | Types '{' ConstVector '}' {
1187 const StructType *STy = dyn_cast<StructType>($1->get());
1189 ThrowException("Cannot make struct constant with type: '" +
1190 (*$1)->getDescription() + "'!");
1192 if ($3->size() != STy->getNumContainedTypes())
1193 ThrowException("Illegal number of initializers for structure type!");
1195 // Check to ensure that constants are compatible with the type initializer!
1196 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1197 if ((*$3)[i]->getType() != STy->getElementType(i))
1198 ThrowException("Expected type '" +
1199 STy->getElementType(i)->getDescription() +
1200 "' for element #" + utostr(i) +
1201 " of structure initializer!");
1203 $$ = ConstantStruct::get(STy, *$3);
1204 delete $1; delete $3;
1207 const StructType *STy = dyn_cast<StructType>($1->get());
1209 ThrowException("Cannot make struct constant with type: '" +
1210 (*$1)->getDescription() + "'!");
1212 if (STy->getNumContainedTypes() != 0)
1213 ThrowException("Illegal number of initializers for structure type!");
1215 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1219 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1221 ThrowException("Cannot make null pointer constant with type: '" +
1222 (*$1)->getDescription() + "'!");
1224 $$ = ConstantPointerNull::get(PTy);
1228 $$ = UndefValue::get($1->get());
1231 | Types SymbolicValueRef {
1232 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1234 ThrowException("Global const reference must be a pointer type!");
1236 // ConstExprs can exist in the body of a function, thus creating
1237 // GlobalValues whenever they refer to a variable. Because we are in
1238 // the context of a function, getValNonImprovising will search the functions
1239 // symbol table instead of the module symbol table for the global symbol,
1240 // which throws things all off. To get around this, we just tell
1241 // getValNonImprovising that we are at global scope here.
1243 Function *SavedCurFn = CurFun.CurrentFunction;
1244 CurFun.CurrentFunction = 0;
1246 Value *V = getValNonImprovising(Ty, $2);
1248 CurFun.CurrentFunction = SavedCurFn;
1250 // If this is an initializer for a constant pointer, which is referencing a
1251 // (currently) undefined variable, create a stub now that shall be replaced
1252 // in the future with the right type of variable.
1255 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1256 const PointerType *PT = cast<PointerType>(Ty);
1258 // First check to see if the forward references value is already created!
1259 PerModuleInfo::GlobalRefsType::iterator I =
1260 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1262 if (I != CurModule.GlobalRefs.end()) {
1263 V = I->second; // Placeholder already exists, use it...
1267 if ($2.Type == ValID::NameVal) Name = $2.Name;
1269 // Create the forward referenced global.
1271 if (const FunctionType *FTy =
1272 dyn_cast<FunctionType>(PT->getElementType())) {
1273 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1274 CurModule.CurrentModule);
1276 GV = new GlobalVariable(PT->getElementType(), false,
1277 GlobalValue::ExternalLinkage, 0,
1278 Name, CurModule.CurrentModule);
1281 // Keep track of the fact that we have a forward ref to recycle it
1282 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1287 $$ = cast<GlobalValue>(V);
1288 delete $1; // Free the type handle
1291 if ($1->get() != $2->getType())
1292 ThrowException("Mismatched types for constant expression!");
1296 | Types ZEROINITIALIZER {
1297 const Type *Ty = $1->get();
1298 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1299 ThrowException("Cannot create a null initialized value of this type!");
1300 $$ = Constant::getNullValue(Ty);
1304 ConstVal : SIntType EINT64VAL { // integral constants
1305 if (!ConstantSInt::isValueValidForType($1, $2))
1306 ThrowException("Constant value doesn't fit in type!");
1307 $$ = ConstantSInt::get($1, $2);
1309 | UIntType EUINT64VAL { // integral constants
1310 if (!ConstantUInt::isValueValidForType($1, $2))
1311 ThrowException("Constant value doesn't fit in type!");
1312 $$ = ConstantUInt::get($1, $2);
1314 | BOOL TRUETOK { // Boolean constants
1315 $$ = ConstantBool::True;
1317 | BOOL FALSETOK { // Boolean constants
1318 $$ = ConstantBool::False;
1320 | FPType FPVAL { // Float & Double constants
1321 $$ = ConstantFP::get($1, $2);
1325 ConstExpr: CAST '(' ConstVal TO Types ')' {
1326 if (!$3->getType()->isFirstClassType())
1327 ThrowException("cast constant expression from a non-primitive type: '" +
1328 $3->getType()->getDescription() + "'!");
1329 if (!$5->get()->isFirstClassType())
1330 ThrowException("cast constant expression to a non-primitive type: '" +
1331 $5->get()->getDescription() + "'!");
1332 $$ = ConstantExpr::getCast($3, $5->get());
1335 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1336 if (!isa<PointerType>($3->getType()))
1337 ThrowException("GetElementPtr requires a pointer operand!");
1339 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1340 // indices to uint struct indices for compatibility.
1341 generic_gep_type_iterator<std::vector<Value*>::iterator>
1342 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1343 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1344 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1345 if (isa<StructType>(*GTI)) // Only change struct indices
1346 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1347 if (CUI->getType() == Type::UByteTy)
1348 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1351 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1353 ThrowException("Index list invalid for constant getelementptr!");
1355 std::vector<Constant*> IdxVec;
1356 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1357 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1358 IdxVec.push_back(C);
1360 ThrowException("Indices to constant getelementptr must be constants!");
1364 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1366 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1367 if ($3->getType() != Type::BoolTy)
1368 ThrowException("Select condition must be of boolean type!");
1369 if ($5->getType() != $7->getType())
1370 ThrowException("Select operand types must match!");
1371 $$ = ConstantExpr::getSelect($3, $5, $7);
1373 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1374 if ($3->getType() != $5->getType())
1375 ThrowException("Binary operator types must match!");
1376 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1377 // To retain backward compatibility with these early compilers, we emit a
1378 // cast to the appropriate integer type automatically if we are in the
1379 // broken case. See PR424 for more information.
1380 if (!isa<PointerType>($3->getType())) {
1381 $$ = ConstantExpr::get($1, $3, $5);
1383 const Type *IntPtrTy = 0;
1384 switch (CurModule.CurrentModule->getPointerSize()) {
1385 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1386 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1387 default: ThrowException("invalid pointer binary constant expr!");
1389 $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1390 ConstantExpr::getCast($5, IntPtrTy));
1391 $$ = ConstantExpr::getCast($$, $3->getType());
1394 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1395 if ($3->getType() != $5->getType())
1396 ThrowException("Logical operator types must match!");
1397 if (!$3->getType()->isIntegral())
1398 ThrowException("Logical operands must have integral types!");
1399 $$ = ConstantExpr::get($1, $3, $5);
1401 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1402 if ($3->getType() != $5->getType())
1403 ThrowException("setcc operand types must match!");
1404 $$ = ConstantExpr::get($1, $3, $5);
1406 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1407 if ($5->getType() != Type::UByteTy)
1408 ThrowException("Shift count for shift constant must be unsigned byte!");
1409 if (!$3->getType()->isInteger())
1410 ThrowException("Shift constant expression requires integer operand!");
1411 $$ = ConstantExpr::get($1, $3, $5);
1415 // ConstVector - A list of comma separated constants.
1416 ConstVector : ConstVector ',' ConstVal {
1417 ($$ = $1)->push_back($3);
1420 $$ = new std::vector<Constant*>();
1425 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1426 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1429 //===----------------------------------------------------------------------===//
1430 // Rules to match Modules
1431 //===----------------------------------------------------------------------===//
1433 // Module rule: Capture the result of parsing the whole file into a result
1436 Module : FunctionList {
1437 $$ = ParserResult = $1;
1438 CurModule.ModuleDone();
1441 // FunctionList - A list of functions, preceeded by a constant pool.
1443 FunctionList : FunctionList Function {
1445 CurFun.FunctionDone();
1447 | FunctionList FunctionProto {
1450 | FunctionList IMPLEMENTATION {
1454 $$ = CurModule.CurrentModule;
1455 // Resolve circular types before we parse the body of the module
1456 ResolveTypes(CurModule.LateResolveTypes);
1459 // ConstPool - Constants with optional names assigned to them.
1460 ConstPool : ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1461 // Eagerly resolve types. This is not an optimization, this is a
1462 // requirement that is due to the fact that we could have this:
1464 // %list = type { %list * }
1465 // %list = type { %list * } ; repeated type decl
1467 // If types are not resolved eagerly, then the two types will not be
1468 // determined to be the same type!
1470 ResolveTypeTo($2, *$4);
1472 if (!setTypeName(*$4, $2) && !$2) {
1473 // If this is a named type that is not a redefinition, add it to the slot
1475 if (inFunctionScope())
1476 CurFun.Types.push_back(*$4);
1478 CurModule.Types.push_back(*$4);
1483 | ConstPool FunctionProto { // Function prototypes can be in const pool
1485 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1486 if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1487 ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1489 | ConstPool OptAssign EXTERNAL GlobalType Types {
1490 ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1493 | ConstPool TARGET TargetDefinition {
1495 | ConstPool DEPLIBS '=' LibrariesDefinition {
1497 | /* empty: end of list */ {
1502 BigOrLittle : BIG { $$ = Module::BigEndian; };
1503 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1505 TargetDefinition : ENDIAN '=' BigOrLittle {
1506 CurModule.CurrentModule->setEndianness($3);
1508 | POINTERSIZE '=' EUINT64VAL {
1510 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1512 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1514 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1516 | TRIPLE '=' STRINGCONSTANT {
1517 CurModule.CurrentModule->setTargetTriple($3);
1521 LibrariesDefinition : '[' LibList ']';
1523 LibList : LibList ',' STRINGCONSTANT {
1524 CurModule.CurrentModule->addLibrary($3);
1528 CurModule.CurrentModule->addLibrary($1);
1531 | /* empty: end of list */ {
1535 //===----------------------------------------------------------------------===//
1536 // Rules to match Function Headers
1537 //===----------------------------------------------------------------------===//
1539 Name : VAR_ID | STRINGCONSTANT;
1540 OptName : Name | /*empty*/ { $$ = 0; };
1542 ArgVal : Types OptName {
1543 if (*$1 == Type::VoidTy)
1544 ThrowException("void typed arguments are invalid!");
1545 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1548 ArgListH : ArgListH ',' ArgVal {
1554 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1559 ArgList : ArgListH {
1562 | ArgListH ',' DOTDOTDOT {
1564 $$->push_back(std::pair<PATypeHolder*,
1565 char*>(new PATypeHolder(Type::VoidTy), 0));
1568 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1569 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1575 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1577 std::string FunctionName($2);
1578 free($2); // Free strdup'd memory!
1580 if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1581 ThrowException("LLVM functions cannot return aggregate types!");
1583 std::vector<const Type*> ParamTypeList;
1584 if ($4) { // If there are arguments...
1585 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1586 I != $4->end(); ++I)
1587 ParamTypeList.push_back(I->first->get());
1590 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1591 if (isVarArg) ParamTypeList.pop_back();
1593 const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1594 const PointerType *PFT = PointerType::get(FT);
1598 if (!FunctionName.empty()) {
1599 ID = ValID::create((char*)FunctionName.c_str());
1601 ID = ValID::create((int)CurModule.Values[PFT].size());
1605 // See if this function was forward referenced. If so, recycle the object.
1606 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1607 // Move the function to the end of the list, from whereever it was
1608 // previously inserted.
1609 Fn = cast<Function>(FWRef);
1610 CurModule.CurrentModule->getFunctionList().remove(Fn);
1611 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1612 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1613 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1614 // If this is the case, either we need to be a forward decl, or it needs
1616 if (!CurFun.isDeclare && !Fn->isExternal())
1617 ThrowException("Redefinition of function '" + FunctionName + "'!");
1619 // Make sure to strip off any argument names so we can't get conflicts.
1620 if (Fn->isExternal())
1621 for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend();
1625 } else { // Not already defined?
1626 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1627 CurModule.CurrentModule);
1628 InsertValue(Fn, CurModule.Values);
1631 CurFun.FunctionStart(Fn);
1633 // Add all of the arguments we parsed to the function...
1634 if ($4) { // Is null if empty...
1635 if (isVarArg) { // Nuke the last entry
1636 assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1637 "Not a varargs marker!");
1638 delete $4->back().first;
1639 $4->pop_back(); // Delete the last entry
1641 Function::aiterator ArgIt = Fn->abegin();
1642 for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1643 I != $4->end(); ++I, ++ArgIt) {
1644 delete I->first; // Delete the typeholder...
1646 setValueName(ArgIt, I->second); // Insert arg into symtab...
1650 delete $4; // We're now done with the argument list
1654 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1656 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1657 $$ = CurFun.CurrentFunction;
1659 // Make sure that we keep track of the linkage type even if there was a
1660 // previous "declare".
1663 // Resolve circular types before we parse the body of the function.
1664 ResolveTypes(CurFun.LateResolveTypes);
1667 END : ENDTOK | '}'; // Allow end of '}' to end a function
1669 Function : BasicBlockList END {
1673 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1674 $$ = CurFun.CurrentFunction;
1675 CurFun.FunctionDone();
1678 //===----------------------------------------------------------------------===//
1679 // Rules to match Basic Blocks
1680 //===----------------------------------------------------------------------===//
1682 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1683 $$ = ValID::create($1);
1686 $$ = ValID::create($1);
1688 | FPVAL { // Perhaps it's an FP constant?
1689 $$ = ValID::create($1);
1692 $$ = ValID::create(ConstantBool::True);
1695 $$ = ValID::create(ConstantBool::False);
1698 $$ = ValID::createNull();
1701 $$ = ValID::createUndef();
1703 | '<' ConstVector '>' { // Nonempty unsized packed vector
1704 const Type *ETy = (*$2)[0]->getType();
1705 int NumElements = $2->size();
1707 PackedType* pt = PackedType::get(ETy, NumElements);
1708 PATypeHolder* PTy = new PATypeHolder(
1716 // Verify all elements are correct type!
1717 for (unsigned i = 0; i < $2->size(); i++) {
1718 if (ETy != (*$2)[i]->getType())
1719 ThrowException("Element #" + utostr(i) + " is not of type '" +
1720 ETy->getDescription() +"' as required!\nIt is of type '" +
1721 (*$2)[i]->getType()->getDescription() + "'.");
1724 $$ = ValID::create(ConstantPacked::get(pt, *$2));
1725 delete PTy; delete $2;
1728 $$ = ValID::create($1);
1731 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1734 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1735 $$ = ValID::create($1);
1737 | Name { // Is it a named reference...?
1738 $$ = ValID::create($1);
1741 // ValueRef - A reference to a definition... either constant or symbolic
1742 ValueRef : SymbolicValueRef | ConstValueRef;
1745 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1746 // type immediately preceeds the value reference, and allows complex constant
1747 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1748 ResolvedVal : Types ValueRef {
1749 $$ = getVal(*$1, $2); delete $1;
1752 BasicBlockList : BasicBlockList BasicBlock {
1755 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1760 // Basic blocks are terminated by branching instructions:
1761 // br, br/cc, switch, ret
1763 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1764 setValueName($3, $2);
1767 $1->getInstList().push_back($3);
1772 InstructionList : InstructionList Inst {
1773 $1->getInstList().push_back($2);
1777 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1779 // Make sure to move the basic block to the correct location in the
1780 // function, instead of leaving it inserted wherever it was first
1782 CurFun.CurrentFunction->getBasicBlockList().remove(CurBB);
1783 CurFun.CurrentFunction->getBasicBlockList().push_back(CurBB);
1786 $$ = CurBB = getBBVal(ValID::create($1), true);
1788 // Make sure to move the basic block to the correct location in the
1789 // function, instead of leaving it inserted wherever it was first
1791 CurFun.CurrentFunction->getBasicBlockList().remove(CurBB);
1792 CurFun.CurrentFunction->getBasicBlockList().push_back(CurBB);
1795 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1796 $$ = new ReturnInst($2);
1798 | RET VOID { // Return with no result...
1799 $$ = new ReturnInst();
1801 | BR LABEL ValueRef { // Unconditional Branch...
1802 $$ = new BranchInst(getBBVal($3));
1803 } // Conditional Branch...
1804 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1805 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1807 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1808 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6));
1811 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1814 S->addCase(I->first, I->second);
1817 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1818 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6));
1821 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO LABEL ValueRef
1822 UNWIND LABEL ValueRef {
1823 const PointerType *PFTy;
1824 const FunctionType *Ty;
1826 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1827 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1828 // Pull out the types of all of the arguments...
1829 std::vector<const Type*> ParamTypes;
1831 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1833 ParamTypes.push_back((*I)->getType());
1836 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1837 if (isVarArg) ParamTypes.pop_back();
1839 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1840 PFTy = PointerType::get(Ty);
1843 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1845 BasicBlock *Normal = getBBVal($9);
1846 BasicBlock *Except = getBBVal($12);
1848 // Create the call node...
1849 if (!$5) { // Has no arguments?
1850 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1851 } else { // Has arguments?
1852 // Loop through FunctionType's arguments and ensure they are specified
1855 FunctionType::param_iterator I = Ty->param_begin();
1856 FunctionType::param_iterator E = Ty->param_end();
1857 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1859 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1860 if ((*ArgI)->getType() != *I)
1861 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1862 (*I)->getDescription() + "'!");
1864 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1865 ThrowException("Invalid number of parameters detected!");
1867 $$ = new InvokeInst(V, Normal, Except, *$5);
1873 $$ = new UnwindInst();
1876 $$ = new UnreachableInst();
1881 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1883 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1885 ThrowException("May only switch on a constant pool value!");
1887 $$->push_back(std::make_pair(V, getBBVal($6)));
1889 | IntType ConstValueRef ',' LABEL ValueRef {
1890 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1891 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1894 ThrowException("May only switch on a constant pool value!");
1896 $$->push_back(std::make_pair(V, getBBVal($5)));
1899 Inst : OptAssign InstVal {
1900 // Is this definition named?? if so, assign the name...
1901 setValueName($2, $1);
1906 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1907 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1908 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
1911 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1913 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1918 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1919 $$ = new std::vector<Value*>();
1922 | ValueRefList ',' ResolvedVal {
1927 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1928 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1930 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1931 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
1932 !isa<PackedType>((*$2).get()))
1934 "Arithmetic operator requires integer, FP, or packed operands!");
1935 if(isa<PackedType>((*$2).get()) && $1 == Instruction::Rem) {
1937 "Rem not supported on packed types!");
1939 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1941 ThrowException("binary operator returned null!");
1944 | LogicalOps Types ValueRef ',' ValueRef {
1945 if (!(*$2)->isIntegral())
1946 ThrowException("Logical operator requires integral operands!");
1947 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1949 ThrowException("binary operator returned null!");
1952 | SetCondOps Types ValueRef ',' ValueRef {
1953 if(isa<PackedType>((*$2).get())) {
1955 "PackedTypes currently not supported in setcc instructions!");
1957 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1959 ThrowException("binary operator returned null!");
1963 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1964 << " Replacing with 'xor'.\n";
1966 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1968 ThrowException("Expected integral type for not instruction!");
1970 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1972 ThrowException("Could not create a xor instruction!");
1974 | ShiftOps ResolvedVal ',' ResolvedVal {
1975 if ($4->getType() != Type::UByteTy)
1976 ThrowException("Shift amount must be ubyte!");
1977 if (!$2->getType()->isInteger())
1978 ThrowException("Shift constant expression requires integer operand!");
1979 $$ = new ShiftInst($1, $2, $4);
1981 | CAST ResolvedVal TO Types {
1982 if (!$4->get()->isFirstClassType())
1983 ThrowException("cast instruction to a non-primitive type: '" +
1984 $4->get()->getDescription() + "'!");
1985 $$ = new CastInst($2, *$4);
1988 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
1989 if ($2->getType() != Type::BoolTy)
1990 ThrowException("select condition must be boolean!");
1991 if ($4->getType() != $6->getType())
1992 ThrowException("select value types should match!");
1993 $$ = new SelectInst($2, $4, $6);
1995 | VA_ARG ResolvedVal ',' Types {
1996 // FIXME: This is emulation code for an obsolete syntax. This should be
1997 // removed at some point.
1998 if (!ObsoleteVarArgs) {
1999 std::cerr << "WARNING: this file uses obsolete features. "
2000 << "Assemble and disassemble to update it.\n";
2001 ObsoleteVarArgs = true;
2004 // First, load the valist...
2005 Instruction *CurVAList = new LoadInst($2, "");
2006 CurBB->getInstList().push_back(CurVAList);
2008 // Emit the vaarg instruction.
2009 $$ = new VAArgInst(CurVAList, *$4);
2011 // Now we must advance the pointer and update it in memory.
2012 Instruction *TheVANext = new VANextInst(CurVAList, *$4);
2013 CurBB->getInstList().push_back(TheVANext);
2015 CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
2018 | VAARG ResolvedVal ',' Types {
2019 $$ = new VAArgInst($2, *$4);
2022 | VANEXT ResolvedVal ',' Types {
2023 $$ = new VANextInst($2, *$4);
2027 const Type *Ty = $2->front().first->getType();
2028 if (!Ty->isFirstClassType())
2029 ThrowException("PHI node operands must be of first class type!");
2030 $$ = new PHINode(Ty);
2031 $$->op_reserve($2->size()*2);
2032 while ($2->begin() != $2->end()) {
2033 if ($2->front().first->getType() != Ty)
2034 ThrowException("All elements of a PHI node must be of the same type!");
2035 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2038 delete $2; // Free the list...
2040 | CALL TypesV ValueRef '(' ValueRefListE ')' {
2041 const PointerType *PFTy;
2042 const FunctionType *Ty;
2044 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
2045 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2046 // Pull out the types of all of the arguments...
2047 std::vector<const Type*> ParamTypes;
2049 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
2051 ParamTypes.push_back((*I)->getType());
2054 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2055 if (isVarArg) ParamTypes.pop_back();
2057 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
2058 PFTy = PointerType::get(Ty);
2061 Value *V = getVal(PFTy, $3); // Get the function we're calling...
2063 // Create the call node...
2064 if (!$5) { // Has no arguments?
2065 // Make sure no arguments is a good thing!
2066 if (Ty->getNumParams() != 0)
2067 ThrowException("No arguments passed to a function that "
2068 "expects arguments!");
2070 $$ = new CallInst(V, std::vector<Value*>());
2071 } else { // Has arguments?
2072 // Loop through FunctionType's arguments and ensure they are specified
2075 FunctionType::param_iterator I = Ty->param_begin();
2076 FunctionType::param_iterator E = Ty->param_end();
2077 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
2079 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2080 if ((*ArgI)->getType() != *I)
2081 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2082 (*I)->getDescription() + "'!");
2084 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2085 ThrowException("Invalid number of parameters detected!");
2087 $$ = new CallInst(V, *$5);
2097 // IndexList - List of indices for GEP based instructions...
2098 IndexList : ',' ValueRefList {
2101 $$ = new std::vector<Value*>();
2104 OptVolatile : VOLATILE {
2112 MemoryInst : MALLOC Types {
2113 $$ = new MallocInst(*$2);
2116 | MALLOC Types ',' UINT ValueRef {
2117 $$ = new MallocInst(*$2, getVal($4, $5));
2121 $$ = new AllocaInst(*$2);
2124 | ALLOCA Types ',' UINT ValueRef {
2125 $$ = new AllocaInst(*$2, getVal($4, $5));
2128 | FREE ResolvedVal {
2129 if (!isa<PointerType>($2->getType()))
2130 ThrowException("Trying to free nonpointer type " +
2131 $2->getType()->getDescription() + "!");
2132 $$ = new FreeInst($2);
2135 | OptVolatile LOAD Types ValueRef {
2136 if (!isa<PointerType>($3->get()))
2137 ThrowException("Can't load from nonpointer type: " +
2138 (*$3)->getDescription());
2139 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2140 ThrowException("Can't load from pointer of non-first-class type: " +
2141 (*$3)->getDescription());
2142 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2145 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2146 const PointerType *PT = dyn_cast<PointerType>($5->get());
2148 ThrowException("Can't store to a nonpointer type: " +
2149 (*$5)->getDescription());
2150 const Type *ElTy = PT->getElementType();
2151 if (ElTy != $3->getType())
2152 ThrowException("Can't store '" + $3->getType()->getDescription() +
2153 "' into space of type '" + ElTy->getDescription() + "'!");
2155 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2158 | GETELEMENTPTR Types ValueRef IndexList {
2159 if (!isa<PointerType>($2->get()))
2160 ThrowException("getelementptr insn requires pointer operand!");
2162 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2163 // indices to uint struct indices for compatibility.
2164 generic_gep_type_iterator<std::vector<Value*>::iterator>
2165 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2166 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2167 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2168 if (isa<StructType>(*GTI)) // Only change struct indices
2169 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2170 if (CUI->getType() == Type::UByteTy)
2171 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2173 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2174 ThrowException("Invalid getelementptr indices for type '" +
2175 (*$2)->getDescription()+ "'!");
2176 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2177 delete $2; delete $4;
2182 int yyerror(const char *ErrorMsg) {
2184 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2185 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2186 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2187 if (yychar == YYEMPTY || yychar == 0)
2188 errMsg += "end-of-file.";
2190 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2191 ThrowException(errMsg);