1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/ADT/STLExtras.h"
27 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
28 int yylex(); // declaration" of xxx warnings.
32 std::string CurFilename;
36 static Module *ParserResult;
38 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
39 // relating to upreferences in the input stream.
41 //#define DEBUG_UPREFS 1
43 #define UR_OUT(X) std::cerr << X
48 #define YYERROR_VERBOSE 1
50 static bool ObsoleteVarArgs;
51 static bool NewVarArgs;
52 static BasicBlock* CurBB;
55 // This contains info used when building the body of a function. It is
56 // destroyed when the function is completed.
58 typedef std::vector<Value *> ValueList; // Numbered defs
60 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
61 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
63 static struct PerModuleInfo {
64 Module *CurrentModule;
65 std::map<const Type *, ValueList> Values; // Module level numbered definitions
66 std::map<const Type *,ValueList> LateResolveValues;
67 std::vector<PATypeHolder> Types;
68 std::map<ValID, PATypeHolder> LateResolveTypes;
70 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
71 /// how they were referenced and one which line of the input they came from so
72 /// that we can resolve them later and print error messages as appropriate.
73 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
75 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
76 // references to global values. Global values may be referenced before they
77 // are defined, and if so, the temporary object that they represent is held
78 // here. This is used for forward references of GlobalValues.
80 typedef std::map<std::pair<const PointerType *,
81 ValID>, GlobalValue*> GlobalRefsType;
82 GlobalRefsType GlobalRefs;
85 // If we could not resolve some functions at function compilation time
86 // (calls to functions before they are defined), resolve them now... Types
87 // are resolved when the constant pool has been completely parsed.
89 ResolveDefinitions(LateResolveValues);
91 // Check to make sure that all global value forward references have been
94 if (!GlobalRefs.empty()) {
95 std::string UndefinedReferences = "Unresolved global references exist:\n";
97 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
99 UndefinedReferences += " " + I->first.first->getDescription() + " " +
100 I->first.second.getName() + "\n";
102 ThrowException(UndefinedReferences);
105 Values.clear(); // Clear out function local definitions
111 // GetForwardRefForGlobal - Check to see if there is a forward reference
112 // for this global. If so, remove it from the GlobalRefs map and return it.
113 // If not, just return null.
114 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
115 // Check to see if there is a forward reference to this global variable...
116 // if there is, eliminate it and patch the reference to use the new def'n.
117 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
118 GlobalValue *Ret = 0;
119 if (I != GlobalRefs.end()) {
127 static struct PerFunctionInfo {
128 Function *CurrentFunction; // Pointer to current function being created
130 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
131 std::map<const Type*, ValueList> LateResolveValues;
132 bool isDeclare; // Is this function a forward declararation?
134 /// BBForwardRefs - When we see forward references to basic blocks, keep
135 /// track of them here.
136 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
137 std::vector<BasicBlock*> NumberedBlocks;
140 inline PerFunctionInfo() {
145 inline void FunctionStart(Function *M) {
150 void FunctionDone() {
151 NumberedBlocks.clear();
153 // Any forward referenced blocks left?
154 if (!BBForwardRefs.empty())
155 ThrowException("Undefined reference to label " +
156 BBForwardRefs.begin()->first->getName());
158 // Resolve all forward references now.
159 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
161 Values.clear(); // Clear out function local definitions
165 } CurFun; // Info for the current function...
167 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
170 //===----------------------------------------------------------------------===//
171 // Code to handle definitions of all the types
172 //===----------------------------------------------------------------------===//
174 static int InsertValue(Value *V,
175 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
176 if (V->hasName()) return -1; // Is this a numbered definition?
178 // Yes, insert the value into the value table...
179 ValueList &List = ValueTab[V->getType()];
181 return List.size()-1;
184 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
186 case ValID::NumberVal: // Is it a numbered definition?
187 // Module constants occupy the lowest numbered slots...
188 if ((unsigned)D.Num < CurModule.Types.size())
189 return CurModule.Types[(unsigned)D.Num];
191 case ValID::NameVal: // Is it a named definition?
192 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
193 D.destroy(); // Free old strdup'd memory...
198 ThrowException("Internal parser error: Invalid symbol type reference!");
201 // If we reached here, we referenced either a symbol that we don't know about
202 // or an id number that hasn't been read yet. We may be referencing something
203 // forward, so just create an entry to be resolved later and get to it...
205 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
208 if (inFunctionScope()) {
209 if (D.Type == ValID::NameVal)
210 ThrowException("Reference to an undefined type: '" + D.getName() + "'");
212 ThrowException("Reference to an undefined type: #" + itostr(D.Num));
215 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
216 if (I != CurModule.LateResolveTypes.end())
219 Type *Typ = OpaqueType::get();
220 CurModule.LateResolveTypes.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 (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
333 ThrowException("Invalid use of a composite type!");
335 // If we reached here, we referenced either a symbol that we don't know about
336 // or an id number that hasn't been read yet. We may be referencing something
337 // forward, so just create an entry to be resolved later and get to it...
339 V = new Argument(Ty);
341 // Remember where this forward reference came from. FIXME, shouldn't we try
342 // to recycle these things??
343 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
346 if (inFunctionScope())
347 InsertValue(V, CurFun.LateResolveValues);
349 InsertValue(V, CurModule.LateResolveValues);
353 /// getBBVal - This is used for two purposes:
354 /// * If isDefinition is true, a new basic block with the specified ID is being
356 /// * If isDefinition is true, this is a reference to a basic block, which may
357 /// or may not be a forward reference.
359 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
360 assert(inFunctionScope() && "Can't get basic block at global scope!");
365 default: ThrowException("Illegal label reference " + ID.getName());
366 case ValID::NumberVal: // Is it a numbered definition?
367 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
368 CurFun.NumberedBlocks.resize(ID.Num+1);
369 BB = CurFun.NumberedBlocks[ID.Num];
371 case ValID::NameVal: // Is it a named definition?
373 if (Value *N = CurFun.CurrentFunction->
374 getSymbolTable().lookup(Type::LabelTy, Name))
375 BB = cast<BasicBlock>(N);
379 // See if the block has already been defined.
381 // If this is the definition of the block, make sure the existing value was
382 // just a forward reference. If it was a forward reference, there will be
383 // an entry for it in the PlaceHolderInfo map.
384 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
385 // The existing value was a definition, not a forward reference.
386 ThrowException("Redefinition of label " + ID.getName());
388 ID.destroy(); // Free strdup'd memory.
392 // Otherwise this block has not been seen before.
393 BB = new BasicBlock("", CurFun.CurrentFunction);
394 if (ID.Type == ValID::NameVal) {
395 BB->setName(ID.Name);
397 CurFun.NumberedBlocks[ID.Num] = BB;
400 // If this is not a definition, keep track of it so we can use it as a forward
403 // Remember where this forward reference came from.
404 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
406 // The forward declaration could have been inserted anywhere in the
407 // function: insert it into the correct place now.
408 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
409 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
416 //===----------------------------------------------------------------------===//
417 // Code to handle forward references in instructions
418 //===----------------------------------------------------------------------===//
420 // This code handles the late binding needed with statements that reference
421 // values not defined yet... for example, a forward branch, or the PHI node for
424 // This keeps a table (CurFun.LateResolveValues) of all such forward references
425 // and back patchs after we are done.
428 // ResolveDefinitions - If we could not resolve some defs at parsing
429 // time (forward branches, phi functions for loops, etc...) resolve the
433 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 // common code from the two 'RunVMAsmParser' functions
728 static Module * RunParser(Module * M) {
730 llvmAsmlineno = 1; // Reset the current line number...
731 ObsoleteVarArgs = false;
734 CurModule.CurrentModule = M;
735 yyparse(); // Parse the file, potentially throwing exception
737 Module *Result = ParserResult;
740 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
743 if ((F = Result->getNamedFunction("llvm.va_start"))
744 && F->getFunctionType()->getNumParams() == 0)
745 ObsoleteVarArgs = true;
746 if((F = Result->getNamedFunction("llvm.va_copy"))
747 && F->getFunctionType()->getNumParams() == 1)
748 ObsoleteVarArgs = true;
751 if (ObsoleteVarArgs && NewVarArgs)
752 ThrowException("This file is corrupt: it uses both new and old style varargs");
754 if(ObsoleteVarArgs) {
755 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
756 if (F->arg_size() != 0)
757 ThrowException("Obsolete va_start takes 0 argument!");
761 //bar = alloca typeof(foo)
765 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
766 const Type* ArgTy = F->getFunctionType()->getReturnType();
767 const Type* ArgTyPtr = PointerType::get(ArgTy);
768 Function* NF = Result->getOrInsertFunction("llvm.va_start",
769 RetTy, ArgTyPtr, (Type *)0);
771 while (!F->use_empty()) {
772 CallInst* CI = cast<CallInst>(F->use_back());
773 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
774 new CallInst(NF, bar, "", CI);
775 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
776 CI->replaceAllUsesWith(foo);
777 CI->getParent()->getInstList().erase(CI);
779 Result->getFunctionList().erase(F);
782 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
783 if(F->arg_size() != 1)
784 ThrowException("Obsolete va_end takes 1 argument!");
788 //bar = alloca 1 of typeof(foo)
790 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
791 const Type* ArgTy = F->getFunctionType()->getParamType(0);
792 const Type* ArgTyPtr = PointerType::get(ArgTy);
793 Function* NF = Result->getOrInsertFunction("llvm.va_end",
794 RetTy, ArgTyPtr, (Type *)0);
796 while (!F->use_empty()) {
797 CallInst* CI = cast<CallInst>(F->use_back());
798 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
799 new StoreInst(CI->getOperand(1), bar, CI);
800 new CallInst(NF, bar, "", CI);
801 CI->getParent()->getInstList().erase(CI);
803 Result->getFunctionList().erase(F);
806 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
807 if(F->arg_size() != 1)
808 ThrowException("Obsolete va_copy takes 1 argument!");
811 //a = alloca 1 of typeof(foo)
812 //b = alloca 1 of typeof(foo)
817 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
818 const Type* ArgTy = F->getFunctionType()->getReturnType();
819 const Type* ArgTyPtr = PointerType::get(ArgTy);
820 Function* NF = Result->getOrInsertFunction("llvm.va_copy",
821 RetTy, ArgTyPtr, ArgTyPtr,
824 while (!F->use_empty()) {
825 CallInst* CI = cast<CallInst>(F->use_back());
826 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
827 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
828 new StoreInst(CI->getOperand(1), b, CI);
829 new CallInst(NF, a, b, "", CI);
830 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
831 CI->replaceAllUsesWith(foo);
832 CI->getParent()->getInstList().erase(CI);
834 Result->getFunctionList().erase(F);
842 //===----------------------------------------------------------------------===//
843 // RunVMAsmParser - Define an interface to this parser
844 //===----------------------------------------------------------------------===//
846 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
849 CurFilename = Filename;
850 return RunParser(new Module(CurFilename));
853 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
854 set_scan_string(AsmString);
856 CurFilename = "from_memory";
858 return RunParser(new Module (CurFilename));
867 llvm::Module *ModuleVal;
868 llvm::Function *FunctionVal;
869 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
870 llvm::BasicBlock *BasicBlockVal;
871 llvm::TerminatorInst *TermInstVal;
872 llvm::Instruction *InstVal;
873 llvm::Constant *ConstVal;
875 const llvm::Type *PrimType;
876 llvm::PATypeHolder *TypeVal;
877 llvm::Value *ValueVal;
879 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
880 std::vector<llvm::Value*> *ValueList;
881 std::list<llvm::PATypeHolder> *TypeList;
882 // Represent the RHS of PHI node
883 std::list<std::pair<llvm::Value*,
884 llvm::BasicBlock*> > *PHIList;
885 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
886 std::vector<llvm::Constant*> *ConstVector;
888 llvm::GlobalValue::LinkageTypes Linkage;
896 char *StrVal; // This memory is strdup'd!
897 llvm::ValID ValIDVal; // strdup'd memory maybe!
899 llvm::Instruction::BinaryOps BinaryOpVal;
900 llvm::Instruction::TermOps TermOpVal;
901 llvm::Instruction::MemoryOps MemOpVal;
902 llvm::Instruction::OtherOps OtherOpVal;
903 llvm::Module::Endianness Endianness;
906 %type <ModuleVal> Module FunctionList
907 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
908 %type <BasicBlockVal> BasicBlock InstructionList
909 %type <TermInstVal> BBTerminatorInst
910 %type <InstVal> Inst InstVal MemoryInst
911 %type <ConstVal> ConstVal ConstExpr
912 %type <ConstVector> ConstVector
913 %type <ArgList> ArgList ArgListH
914 %type <ArgVal> ArgVal
915 %type <PHIList> PHIList
916 %type <ValueList> ValueRefList ValueRefListE // For call param lists
917 %type <ValueList> IndexList // For GEP derived indices
918 %type <TypeList> TypeListI ArgTypeListI
919 %type <JumpTable> JumpTable
920 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
921 %type <BoolVal> OptVolatile // 'volatile' or not
922 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
923 %type <Linkage> OptLinkage
924 %type <Endianness> BigOrLittle
926 // ValueRef - Unresolved reference to a definition or BB
927 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
928 %type <ValueVal> ResolvedVal // <type> <valref> pair
929 // Tokens and types for handling constant integer values
931 // ESINT64VAL - A negative number within long long range
932 %token <SInt64Val> ESINT64VAL
934 // EUINT64VAL - A positive number within uns. long long range
935 %token <UInt64Val> EUINT64VAL
936 %type <SInt64Val> EINT64VAL
938 %token <SIntVal> SINTVAL // Signed 32 bit ints...
939 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
940 %type <SIntVal> INTVAL
941 %token <FPVal> FPVAL // Float or Double constant
944 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
945 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
946 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
947 %token <PrimType> FLOAT DOUBLE TYPE LABEL
949 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
950 %type <StrVal> Name OptName OptAssign
953 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
954 %token DECLARE GLOBAL CONSTANT VOLATILE
955 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
956 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG
957 %token DEPLIBS CALL TAIL
958 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK
959 %type <UIntVal> OptCallingConv
961 // Basic Block Terminating Operators
962 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
965 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
966 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
967 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
969 // Memory Instructions
970 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
973 %type <OtherOpVal> ShiftOps
974 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG
975 %token VAARG_old VANEXT_old //OBSOLETE
981 // Handle constant integer size restriction and conversion...
985 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
986 ThrowException("Value too large for type!");
991 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
992 EINT64VAL : EUINT64VAL {
993 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
994 ThrowException("Value too large for type!");
998 // Operations that are notably excluded from this list include:
999 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1001 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1002 LogicalOps : AND | OR | XOR;
1003 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1005 ShiftOps : SHL | SHR;
1007 // These are some types that allow classification if we only want a particular
1008 // thing... for example, only a signed, unsigned, or integral type.
1009 SIntType : LONG | INT | SHORT | SBYTE;
1010 UIntType : ULONG | UINT | USHORT | UBYTE;
1011 IntType : SIntType | UIntType;
1012 FPType : FLOAT | DOUBLE;
1014 // OptAssign - Value producing statements have an optional assignment component
1015 OptAssign : Name '=' {
1022 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1023 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1024 WEAK { $$ = GlobalValue::WeakLinkage; } |
1025 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1026 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1028 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1029 CCC_TOK { $$ = CallingConv::C; } |
1030 FASTCC_TOK { $$ = CallingConv::Fast; } |
1031 COLDCC_TOK { $$ = CallingConv::Cold; } |
1033 if ((unsigned)$2 != $2)
1034 ThrowException("Calling conv too large!");
1038 //===----------------------------------------------------------------------===//
1039 // Types includes all predefined types... except void, because it can only be
1040 // used in specific contexts (function returning void for example). To have
1041 // access to it, a user must explicitly use TypesV.
1044 // TypesV includes all of 'Types', but it also includes the void type.
1045 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1046 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1049 if (!UpRefs.empty())
1050 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
1055 // Derived types are added later...
1057 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1058 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1060 $$ = new PATypeHolder(OpaqueType::get());
1063 $$ = new PATypeHolder($1);
1065 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1066 $$ = new PATypeHolder(getTypeVal($1));
1069 // Include derived types in the Types production.
1071 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1072 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1073 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1074 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1075 $$ = new PATypeHolder(OT);
1076 UR_OUT("New Upreference!\n");
1078 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1079 std::vector<const Type*> Params;
1080 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1081 E = $3->end(); I != E; ++I)
1082 Params.push_back(*I);
1083 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1084 if (isVarArg) Params.pop_back();
1086 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1087 delete $3; // Delete the argument list
1088 delete $1; // Delete the return type handle
1090 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1091 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1094 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1095 const llvm::Type* ElemTy = $4->get();
1096 if ((unsigned)$2 != $2) {
1097 ThrowException("Unsigned result not equal to signed result");
1099 if(!ElemTy->isPrimitiveType()) {
1100 ThrowException("Elemental type of a PackedType must be primitive");
1102 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1105 | '{' TypeListI '}' { // Structure type?
1106 std::vector<const Type*> Elements;
1107 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1108 E = $2->end(); I != E; ++I)
1109 Elements.push_back(*I);
1111 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1114 | '{' '}' { // Empty structure type?
1115 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1117 | UpRTypes '*' { // Pointer type?
1118 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1122 // TypeList - Used for struct declarations and as a basis for function type
1123 // declaration type lists
1125 TypeListI : UpRTypes {
1126 $$ = new std::list<PATypeHolder>();
1127 $$->push_back(*$1); delete $1;
1129 | TypeListI ',' UpRTypes {
1130 ($$=$1)->push_back(*$3); delete $3;
1133 // ArgTypeList - List of types for a function type declaration...
1134 ArgTypeListI : TypeListI
1135 | TypeListI ',' DOTDOTDOT {
1136 ($$=$1)->push_back(Type::VoidTy);
1139 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1142 $$ = new std::list<PATypeHolder>();
1145 // ConstVal - The various declarations that go into the constant pool. This
1146 // production is used ONLY to represent constants that show up AFTER a 'const',
1147 // 'constant' or 'global' token at global scope. Constants that can be inlined
1148 // into other expressions (such as integers and constexprs) are handled by the
1149 // ResolvedVal, ValueRef and ConstValueRef productions.
1151 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1152 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1154 ThrowException("Cannot make array constant with type: '" +
1155 (*$1)->getDescription() + "'!");
1156 const Type *ETy = ATy->getElementType();
1157 int NumElements = ATy->getNumElements();
1159 // Verify that we have the correct size...
1160 if (NumElements != -1 && NumElements != (int)$3->size())
1161 ThrowException("Type mismatch: constant sized array initialized with " +
1162 utostr($3->size()) + " arguments, but has size of " +
1163 itostr(NumElements) + "!");
1165 // Verify all elements are correct type!
1166 for (unsigned i = 0; i < $3->size(); i++) {
1167 if (ETy != (*$3)[i]->getType())
1168 ThrowException("Element #" + utostr(i) + " is not of type '" +
1169 ETy->getDescription() +"' as required!\nIt is of type '"+
1170 (*$3)[i]->getType()->getDescription() + "'.");
1173 $$ = ConstantArray::get(ATy, *$3);
1174 delete $1; delete $3;
1177 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1179 ThrowException("Cannot make array constant with type: '" +
1180 (*$1)->getDescription() + "'!");
1182 int NumElements = ATy->getNumElements();
1183 if (NumElements != -1 && NumElements != 0)
1184 ThrowException("Type mismatch: constant sized array initialized with 0"
1185 " arguments, but has size of " + itostr(NumElements) +"!");
1186 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1189 | Types 'c' STRINGCONSTANT {
1190 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1192 ThrowException("Cannot make array constant with type: '" +
1193 (*$1)->getDescription() + "'!");
1195 int NumElements = ATy->getNumElements();
1196 const Type *ETy = ATy->getElementType();
1197 char *EndStr = UnEscapeLexed($3, true);
1198 if (NumElements != -1 && NumElements != (EndStr-$3))
1199 ThrowException("Can't build string constant of size " +
1200 itostr((int)(EndStr-$3)) +
1201 " when array has size " + itostr(NumElements) + "!");
1202 std::vector<Constant*> Vals;
1203 if (ETy == Type::SByteTy) {
1204 for (char *C = $3; C != EndStr; ++C)
1205 Vals.push_back(ConstantSInt::get(ETy, *C));
1206 } else if (ETy == Type::UByteTy) {
1207 for (char *C = $3; C != EndStr; ++C)
1208 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1211 ThrowException("Cannot build string arrays of non byte sized elements!");
1214 $$ = ConstantArray::get(ATy, Vals);
1217 | Types '<' ConstVector '>' { // Nonempty unsized arr
1218 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1220 ThrowException("Cannot make packed constant with type: '" +
1221 (*$1)->getDescription() + "'!");
1222 const Type *ETy = PTy->getElementType();
1223 int NumElements = PTy->getNumElements();
1225 // Verify that we have the correct size...
1226 if (NumElements != -1 && NumElements != (int)$3->size())
1227 ThrowException("Type mismatch: constant sized packed initialized with " +
1228 utostr($3->size()) + " arguments, but has size of " +
1229 itostr(NumElements) + "!");
1231 // Verify all elements are correct type!
1232 for (unsigned i = 0; i < $3->size(); i++) {
1233 if (ETy != (*$3)[i]->getType())
1234 ThrowException("Element #" + utostr(i) + " is not of type '" +
1235 ETy->getDescription() +"' as required!\nIt is of type '"+
1236 (*$3)[i]->getType()->getDescription() + "'.");
1239 $$ = ConstantPacked::get(PTy, *$3);
1240 delete $1; delete $3;
1242 | Types '{' ConstVector '}' {
1243 const StructType *STy = dyn_cast<StructType>($1->get());
1245 ThrowException("Cannot make struct constant with type: '" +
1246 (*$1)->getDescription() + "'!");
1248 if ($3->size() != STy->getNumContainedTypes())
1249 ThrowException("Illegal number of initializers for structure type!");
1251 // Check to ensure that constants are compatible with the type initializer!
1252 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1253 if ((*$3)[i]->getType() != STy->getElementType(i))
1254 ThrowException("Expected type '" +
1255 STy->getElementType(i)->getDescription() +
1256 "' for element #" + utostr(i) +
1257 " of structure initializer!");
1259 $$ = ConstantStruct::get(STy, *$3);
1260 delete $1; delete $3;
1263 const StructType *STy = dyn_cast<StructType>($1->get());
1265 ThrowException("Cannot make struct constant with type: '" +
1266 (*$1)->getDescription() + "'!");
1268 if (STy->getNumContainedTypes() != 0)
1269 ThrowException("Illegal number of initializers for structure type!");
1271 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1275 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1277 ThrowException("Cannot make null pointer constant with type: '" +
1278 (*$1)->getDescription() + "'!");
1280 $$ = ConstantPointerNull::get(PTy);
1284 $$ = UndefValue::get($1->get());
1287 | Types SymbolicValueRef {
1288 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1290 ThrowException("Global const reference must be a pointer type!");
1292 // ConstExprs can exist in the body of a function, thus creating
1293 // GlobalValues whenever they refer to a variable. Because we are in
1294 // the context of a function, getValNonImprovising will search the functions
1295 // symbol table instead of the module symbol table for the global symbol,
1296 // which throws things all off. To get around this, we just tell
1297 // getValNonImprovising that we are at global scope here.
1299 Function *SavedCurFn = CurFun.CurrentFunction;
1300 CurFun.CurrentFunction = 0;
1302 Value *V = getValNonImprovising(Ty, $2);
1304 CurFun.CurrentFunction = SavedCurFn;
1306 // If this is an initializer for a constant pointer, which is referencing a
1307 // (currently) undefined variable, create a stub now that shall be replaced
1308 // in the future with the right type of variable.
1311 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1312 const PointerType *PT = cast<PointerType>(Ty);
1314 // First check to see if the forward references value is already created!
1315 PerModuleInfo::GlobalRefsType::iterator I =
1316 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1318 if (I != CurModule.GlobalRefs.end()) {
1319 V = I->second; // Placeholder already exists, use it...
1323 if ($2.Type == ValID::NameVal) Name = $2.Name;
1325 // Create the forward referenced global.
1327 if (const FunctionType *FTy =
1328 dyn_cast<FunctionType>(PT->getElementType())) {
1329 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1330 CurModule.CurrentModule);
1332 GV = new GlobalVariable(PT->getElementType(), false,
1333 GlobalValue::ExternalLinkage, 0,
1334 Name, CurModule.CurrentModule);
1337 // Keep track of the fact that we have a forward ref to recycle it
1338 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1343 $$ = cast<GlobalValue>(V);
1344 delete $1; // Free the type handle
1347 if ($1->get() != $2->getType())
1348 ThrowException("Mismatched types for constant expression!");
1352 | Types ZEROINITIALIZER {
1353 const Type *Ty = $1->get();
1354 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1355 ThrowException("Cannot create a null initialized value of this type!");
1356 $$ = Constant::getNullValue(Ty);
1360 ConstVal : SIntType EINT64VAL { // integral constants
1361 if (!ConstantSInt::isValueValidForType($1, $2))
1362 ThrowException("Constant value doesn't fit in type!");
1363 $$ = ConstantSInt::get($1, $2);
1365 | UIntType EUINT64VAL { // integral constants
1366 if (!ConstantUInt::isValueValidForType($1, $2))
1367 ThrowException("Constant value doesn't fit in type!");
1368 $$ = ConstantUInt::get($1, $2);
1370 | BOOL TRUETOK { // Boolean constants
1371 $$ = ConstantBool::True;
1373 | BOOL FALSETOK { // Boolean constants
1374 $$ = ConstantBool::False;
1376 | FPType FPVAL { // Float & Double constants
1377 if (!ConstantFP::isValueValidForType($1, $2))
1378 ThrowException("Floating point constant invalid for type!!");
1379 $$ = ConstantFP::get($1, $2);
1383 ConstExpr: CAST '(' ConstVal TO Types ')' {
1384 if (!$3->getType()->isFirstClassType())
1385 ThrowException("cast constant expression from a non-primitive type: '" +
1386 $3->getType()->getDescription() + "'!");
1387 if (!$5->get()->isFirstClassType())
1388 ThrowException("cast constant expression to a non-primitive type: '" +
1389 $5->get()->getDescription() + "'!");
1390 $$ = ConstantExpr::getCast($3, $5->get());
1393 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1394 if (!isa<PointerType>($3->getType()))
1395 ThrowException("GetElementPtr requires a pointer operand!");
1397 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1398 // indices to uint struct indices for compatibility.
1399 generic_gep_type_iterator<std::vector<Value*>::iterator>
1400 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1401 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1402 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1403 if (isa<StructType>(*GTI)) // Only change struct indices
1404 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1405 if (CUI->getType() == Type::UByteTy)
1406 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1409 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1411 ThrowException("Index list invalid for constant getelementptr!");
1413 std::vector<Constant*> IdxVec;
1414 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1415 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1416 IdxVec.push_back(C);
1418 ThrowException("Indices to constant getelementptr must be constants!");
1422 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1424 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1425 if ($3->getType() != Type::BoolTy)
1426 ThrowException("Select condition must be of boolean type!");
1427 if ($5->getType() != $7->getType())
1428 ThrowException("Select operand types must match!");
1429 $$ = ConstantExpr::getSelect($3, $5, $7);
1431 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1432 if ($3->getType() != $5->getType())
1433 ThrowException("Binary operator types must match!");
1434 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1435 // To retain backward compatibility with these early compilers, we emit a
1436 // cast to the appropriate integer type automatically if we are in the
1437 // broken case. See PR424 for more information.
1438 if (!isa<PointerType>($3->getType())) {
1439 $$ = ConstantExpr::get($1, $3, $5);
1441 const Type *IntPtrTy = 0;
1442 switch (CurModule.CurrentModule->getPointerSize()) {
1443 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1444 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1445 default: ThrowException("invalid pointer binary constant expr!");
1447 $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1448 ConstantExpr::getCast($5, IntPtrTy));
1449 $$ = ConstantExpr::getCast($$, $3->getType());
1452 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1453 if ($3->getType() != $5->getType())
1454 ThrowException("Logical operator types must match!");
1455 if (!$3->getType()->isIntegral())
1456 ThrowException("Logical operands must have integral types!");
1457 $$ = ConstantExpr::get($1, $3, $5);
1459 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1460 if ($3->getType() != $5->getType())
1461 ThrowException("setcc operand types must match!");
1462 $$ = ConstantExpr::get($1, $3, $5);
1464 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1465 if ($5->getType() != Type::UByteTy)
1466 ThrowException("Shift count for shift constant must be unsigned byte!");
1467 if (!$3->getType()->isInteger())
1468 ThrowException("Shift constant expression requires integer operand!");
1469 $$ = ConstantExpr::get($1, $3, $5);
1473 // ConstVector - A list of comma separated constants.
1474 ConstVector : ConstVector ',' ConstVal {
1475 ($$ = $1)->push_back($3);
1478 $$ = new std::vector<Constant*>();
1483 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1484 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1487 //===----------------------------------------------------------------------===//
1488 // Rules to match Modules
1489 //===----------------------------------------------------------------------===//
1491 // Module rule: Capture the result of parsing the whole file into a result
1494 Module : FunctionList {
1495 $$ = ParserResult = $1;
1496 CurModule.ModuleDone();
1499 // FunctionList - A list of functions, preceeded by a constant pool.
1501 FunctionList : FunctionList Function {
1503 CurFun.FunctionDone();
1505 | FunctionList FunctionProto {
1508 | FunctionList IMPLEMENTATION {
1512 $$ = CurModule.CurrentModule;
1513 // Emit an error if there are any unresolved types left.
1514 if (!CurModule.LateResolveTypes.empty()) {
1515 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1516 if (DID.Type == ValID::NameVal)
1517 ThrowException("Reference to an undefined type: '"+DID.getName() + "'");
1519 ThrowException("Reference to an undefined type: #" + itostr(DID.Num));
1523 // ConstPool - Constants with optional names assigned to them.
1524 ConstPool : ConstPool OptAssign TYPE TypesV {
1525 // Eagerly resolve types. This is not an optimization, this is a
1526 // requirement that is due to the fact that we could have this:
1528 // %list = type { %list * }
1529 // %list = type { %list * } ; repeated type decl
1531 // If types are not resolved eagerly, then the two types will not be
1532 // determined to be the same type!
1534 ResolveTypeTo($2, *$4);
1536 if (!setTypeName(*$4, $2) && !$2) {
1537 // If this is a named type that is not a redefinition, add it to the slot
1539 CurModule.Types.push_back(*$4);
1544 | ConstPool FunctionProto { // Function prototypes can be in const pool
1546 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1547 if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1548 ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1550 | ConstPool OptAssign EXTERNAL GlobalType Types {
1551 ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1554 | ConstPool TARGET TargetDefinition {
1556 | ConstPool DEPLIBS '=' LibrariesDefinition {
1558 | /* empty: end of list */ {
1563 BigOrLittle : BIG { $$ = Module::BigEndian; };
1564 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1566 TargetDefinition : ENDIAN '=' BigOrLittle {
1567 CurModule.CurrentModule->setEndianness($3);
1569 | POINTERSIZE '=' EUINT64VAL {
1571 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1573 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1575 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1577 | TRIPLE '=' STRINGCONSTANT {
1578 CurModule.CurrentModule->setTargetTriple($3);
1582 LibrariesDefinition : '[' LibList ']';
1584 LibList : LibList ',' STRINGCONSTANT {
1585 CurModule.CurrentModule->addLibrary($3);
1589 CurModule.CurrentModule->addLibrary($1);
1592 | /* empty: end of list */ {
1596 //===----------------------------------------------------------------------===//
1597 // Rules to match Function Headers
1598 //===----------------------------------------------------------------------===//
1600 Name : VAR_ID | STRINGCONSTANT;
1601 OptName : Name | /*empty*/ { $$ = 0; };
1603 ArgVal : Types OptName {
1604 if (*$1 == Type::VoidTy)
1605 ThrowException("void typed arguments are invalid!");
1606 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1609 ArgListH : ArgListH ',' ArgVal {
1615 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1620 ArgList : ArgListH {
1623 | ArgListH ',' DOTDOTDOT {
1625 $$->push_back(std::pair<PATypeHolder*,
1626 char*>(new PATypeHolder(Type::VoidTy), 0));
1629 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1630 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1636 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')' {
1638 std::string FunctionName($3);
1639 free($3); // Free strdup'd memory!
1641 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1642 ThrowException("LLVM functions cannot return aggregate types!");
1644 std::vector<const Type*> ParamTypeList;
1645 if ($5) { // If there are arguments...
1646 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1647 I != $5->end(); ++I)
1648 ParamTypeList.push_back(I->first->get());
1651 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1652 if (isVarArg) ParamTypeList.pop_back();
1654 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1655 const PointerType *PFT = PointerType::get(FT);
1659 if (!FunctionName.empty()) {
1660 ID = ValID::create((char*)FunctionName.c_str());
1662 ID = ValID::create((int)CurModule.Values[PFT].size());
1666 // See if this function was forward referenced. If so, recycle the object.
1667 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1668 // Move the function to the end of the list, from whereever it was
1669 // previously inserted.
1670 Fn = cast<Function>(FWRef);
1671 CurModule.CurrentModule->getFunctionList().remove(Fn);
1672 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1673 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1674 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1675 // If this is the case, either we need to be a forward decl, or it needs
1677 if (!CurFun.isDeclare && !Fn->isExternal())
1678 ThrowException("Redefinition of function '" + FunctionName + "'!");
1680 // Make sure to strip off any argument names so we can't get conflicts.
1681 if (Fn->isExternal())
1682 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1686 } else { // Not already defined?
1687 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1688 CurModule.CurrentModule);
1689 InsertValue(Fn, CurModule.Values);
1692 CurFun.FunctionStart(Fn);
1693 Fn->setCallingConv($1);
1695 // Add all of the arguments we parsed to the function...
1696 if ($5) { // Is null if empty...
1697 if (isVarArg) { // Nuke the last entry
1698 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1699 "Not a varargs marker!");
1700 delete $5->back().first;
1701 $5->pop_back(); // Delete the last entry
1703 Function::arg_iterator ArgIt = Fn->arg_begin();
1704 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1705 I != $5->end(); ++I, ++ArgIt) {
1706 delete I->first; // Delete the typeholder...
1708 setValueName(ArgIt, I->second); // Insert arg into symtab...
1712 delete $5; // We're now done with the argument list
1716 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1718 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1719 $$ = CurFun.CurrentFunction;
1721 // Make sure that we keep track of the linkage type even if there was a
1722 // previous "declare".
1726 END : ENDTOK | '}'; // Allow end of '}' to end a function
1728 Function : BasicBlockList END {
1732 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1733 $$ = CurFun.CurrentFunction;
1734 CurFun.FunctionDone();
1737 //===----------------------------------------------------------------------===//
1738 // Rules to match Basic Blocks
1739 //===----------------------------------------------------------------------===//
1741 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1742 $$ = ValID::create($1);
1745 $$ = ValID::create($1);
1747 | FPVAL { // Perhaps it's an FP constant?
1748 $$ = ValID::create($1);
1751 $$ = ValID::create(ConstantBool::True);
1754 $$ = ValID::create(ConstantBool::False);
1757 $$ = ValID::createNull();
1760 $$ = ValID::createUndef();
1762 | '<' ConstVector '>' { // Nonempty unsized packed vector
1763 const Type *ETy = (*$2)[0]->getType();
1764 int NumElements = $2->size();
1766 PackedType* pt = PackedType::get(ETy, NumElements);
1767 PATypeHolder* PTy = new PATypeHolder(
1775 // Verify all elements are correct type!
1776 for (unsigned i = 0; i < $2->size(); i++) {
1777 if (ETy != (*$2)[i]->getType())
1778 ThrowException("Element #" + utostr(i) + " is not of type '" +
1779 ETy->getDescription() +"' as required!\nIt is of type '" +
1780 (*$2)[i]->getType()->getDescription() + "'.");
1783 $$ = ValID::create(ConstantPacked::get(pt, *$2));
1784 delete PTy; delete $2;
1787 $$ = ValID::create($1);
1790 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1793 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1794 $$ = ValID::create($1);
1796 | Name { // Is it a named reference...?
1797 $$ = ValID::create($1);
1800 // ValueRef - A reference to a definition... either constant or symbolic
1801 ValueRef : SymbolicValueRef | ConstValueRef;
1804 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1805 // type immediately preceeds the value reference, and allows complex constant
1806 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1807 ResolvedVal : Types ValueRef {
1808 $$ = getVal(*$1, $2); delete $1;
1811 BasicBlockList : BasicBlockList BasicBlock {
1814 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1819 // Basic blocks are terminated by branching instructions:
1820 // br, br/cc, switch, ret
1822 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1823 setValueName($3, $2);
1826 $1->getInstList().push_back($3);
1831 InstructionList : InstructionList Inst {
1832 $1->getInstList().push_back($2);
1836 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1838 // Make sure to move the basic block to the correct location in the
1839 // function, instead of leaving it inserted wherever it was first
1841 Function::BasicBlockListType &BBL =
1842 CurFun.CurrentFunction->getBasicBlockList();
1843 BBL.splice(BBL.end(), BBL, $$);
1846 $$ = CurBB = getBBVal(ValID::create($1), true);
1848 // Make sure to move the basic block to the correct location in the
1849 // function, instead of leaving it inserted wherever it was first
1851 Function::BasicBlockListType &BBL =
1852 CurFun.CurrentFunction->getBasicBlockList();
1853 BBL.splice(BBL.end(), BBL, $$);
1856 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1857 $$ = new ReturnInst($2);
1859 | RET VOID { // Return with no result...
1860 $$ = new ReturnInst();
1862 | BR LABEL ValueRef { // Unconditional Branch...
1863 $$ = new BranchInst(getBBVal($3));
1864 } // Conditional Branch...
1865 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1866 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1868 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1869 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
1872 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1874 for (; I != E; ++I) {
1875 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
1876 S->addCase(CI, I->second);
1878 ThrowException("Switch case is constant, but not a simple integer!");
1882 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1883 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
1886 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1887 TO LABEL ValueRef UNWIND LABEL ValueRef {
1888 const PointerType *PFTy;
1889 const FunctionType *Ty;
1891 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
1892 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1893 // Pull out the types of all of the arguments...
1894 std::vector<const Type*> ParamTypes;
1896 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
1898 ParamTypes.push_back((*I)->getType());
1901 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1902 if (isVarArg) ParamTypes.pop_back();
1904 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
1905 PFTy = PointerType::get(Ty);
1908 Value *V = getVal(PFTy, $4); // Get the function we're calling...
1910 BasicBlock *Normal = getBBVal($10);
1911 BasicBlock *Except = getBBVal($13);
1913 // Create the call node...
1914 if (!$6) { // Has no arguments?
1915 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1916 } else { // Has arguments?
1917 // Loop through FunctionType's arguments and ensure they are specified
1920 FunctionType::param_iterator I = Ty->param_begin();
1921 FunctionType::param_iterator E = Ty->param_end();
1922 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
1924 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1925 if ((*ArgI)->getType() != *I)
1926 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1927 (*I)->getDescription() + "'!");
1929 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1930 ThrowException("Invalid number of parameters detected!");
1932 $$ = new InvokeInst(V, Normal, Except, *$6);
1934 cast<InvokeInst>($$)->setCallingConv($2);
1940 $$ = new UnwindInst();
1943 $$ = new UnreachableInst();
1948 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1950 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1952 ThrowException("May only switch on a constant pool value!");
1954 $$->push_back(std::make_pair(V, getBBVal($6)));
1956 | IntType ConstValueRef ',' LABEL ValueRef {
1957 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1958 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1961 ThrowException("May only switch on a constant pool value!");
1963 $$->push_back(std::make_pair(V, getBBVal($5)));
1966 Inst : OptAssign InstVal {
1967 // Is this definition named?? if so, assign the name...
1968 setValueName($2, $1);
1973 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1974 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1975 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
1978 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1980 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1985 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1986 $$ = new std::vector<Value*>();
1989 | ValueRefList ',' ResolvedVal {
1994 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1995 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1997 OptTailCall : TAIL CALL {
2006 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2007 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2008 !isa<PackedType>((*$2).get()))
2010 "Arithmetic operator requires integer, FP, or packed operands!");
2011 if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
2012 ThrowException("Rem not supported on packed types!");
2013 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2015 ThrowException("binary operator returned null!");
2018 | LogicalOps Types ValueRef ',' ValueRef {
2019 if (!(*$2)->isIntegral())
2020 ThrowException("Logical operator requires integral operands!");
2021 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2023 ThrowException("binary operator returned null!");
2026 | SetCondOps Types ValueRef ',' ValueRef {
2027 if(isa<PackedType>((*$2).get())) {
2029 "PackedTypes currently not supported in setcc instructions!");
2031 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
2033 ThrowException("binary operator returned null!");
2037 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2038 << " Replacing with 'xor'.\n";
2040 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2042 ThrowException("Expected integral type for not instruction!");
2044 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2046 ThrowException("Could not create a xor instruction!");
2048 | ShiftOps ResolvedVal ',' ResolvedVal {
2049 if ($4->getType() != Type::UByteTy)
2050 ThrowException("Shift amount must be ubyte!");
2051 if (!$2->getType()->isInteger())
2052 ThrowException("Shift constant expression requires integer operand!");
2053 $$ = new ShiftInst($1, $2, $4);
2055 | CAST ResolvedVal TO Types {
2056 if (!$4->get()->isFirstClassType())
2057 ThrowException("cast instruction to a non-primitive type: '" +
2058 $4->get()->getDescription() + "'!");
2059 $$ = new CastInst($2, *$4);
2062 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2063 if ($2->getType() != Type::BoolTy)
2064 ThrowException("select condition must be boolean!");
2065 if ($4->getType() != $6->getType())
2066 ThrowException("select value types should match!");
2067 $$ = new SelectInst($2, $4, $6);
2069 | VAARG ResolvedVal ',' Types {
2071 $$ = new VAArgInst($2, *$4);
2074 | VAARG_old ResolvedVal ',' Types {
2075 ObsoleteVarArgs = true;
2076 const Type* ArgTy = $2->getType();
2077 Function* NF = CurModule.CurrentModule->
2078 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2081 //foo = alloca 1 of t
2085 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2086 CurBB->getInstList().push_back(foo);
2087 CallInst* bar = new CallInst(NF, $2);
2088 CurBB->getInstList().push_back(bar);
2089 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2090 $$ = new VAArgInst(foo, *$4);
2093 | VANEXT_old ResolvedVal ',' Types {
2094 ObsoleteVarArgs = true;
2095 const Type* ArgTy = $2->getType();
2096 Function* NF = CurModule.CurrentModule->
2097 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2099 //b = vanext a, t ->
2100 //foo = alloca 1 of t
2103 //tmp = vaarg foo, t
2105 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2106 CurBB->getInstList().push_back(foo);
2107 CallInst* bar = new CallInst(NF, $2);
2108 CurBB->getInstList().push_back(bar);
2109 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2110 Instruction* tmp = new VAArgInst(foo, *$4);
2111 CurBB->getInstList().push_back(tmp);
2112 $$ = new LoadInst(foo);
2116 const Type *Ty = $2->front().first->getType();
2117 if (!Ty->isFirstClassType())
2118 ThrowException("PHI node operands must be of first class type!");
2119 $$ = new PHINode(Ty);
2120 ((PHINode*)$$)->reserveOperandSpace($2->size());
2121 while ($2->begin() != $2->end()) {
2122 if ($2->front().first->getType() != Ty)
2123 ThrowException("All elements of a PHI node must be of the same type!");
2124 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2127 delete $2; // Free the list...
2129 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2130 const PointerType *PFTy;
2131 const FunctionType *Ty;
2133 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2134 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2135 // Pull out the types of all of the arguments...
2136 std::vector<const Type*> ParamTypes;
2138 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2140 ParamTypes.push_back((*I)->getType());
2143 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2144 if (isVarArg) ParamTypes.pop_back();
2146 if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2147 ThrowException("LLVM functions cannot return aggregate types!");
2149 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2150 PFTy = PointerType::get(Ty);
2153 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2155 // Create the call node...
2156 if (!$6) { // Has no arguments?
2157 // Make sure no arguments is a good thing!
2158 if (Ty->getNumParams() != 0)
2159 ThrowException("No arguments passed to a function that "
2160 "expects arguments!");
2162 $$ = new CallInst(V, std::vector<Value*>());
2163 } else { // Has arguments?
2164 // Loop through FunctionType's arguments and ensure they are specified
2167 FunctionType::param_iterator I = Ty->param_begin();
2168 FunctionType::param_iterator E = Ty->param_end();
2169 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2171 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2172 if ((*ArgI)->getType() != *I)
2173 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2174 (*I)->getDescription() + "'!");
2176 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2177 ThrowException("Invalid number of parameters detected!");
2179 $$ = new CallInst(V, *$6);
2181 cast<CallInst>($$)->setTailCall($1);
2182 cast<CallInst>($$)->setCallingConv($2);
2191 // IndexList - List of indices for GEP based instructions...
2192 IndexList : ',' ValueRefList {
2195 $$ = new std::vector<Value*>();
2198 OptVolatile : VOLATILE {
2207 MemoryInst : MALLOC Types {
2208 $$ = new MallocInst(*$2);
2211 | MALLOC Types ',' UINT ValueRef {
2212 $$ = new MallocInst(*$2, getVal($4, $5));
2216 $$ = new AllocaInst(*$2);
2219 | ALLOCA Types ',' UINT ValueRef {
2220 $$ = new AllocaInst(*$2, getVal($4, $5));
2223 | FREE ResolvedVal {
2224 if (!isa<PointerType>($2->getType()))
2225 ThrowException("Trying to free nonpointer type " +
2226 $2->getType()->getDescription() + "!");
2227 $$ = new FreeInst($2);
2230 | OptVolatile LOAD Types ValueRef {
2231 if (!isa<PointerType>($3->get()))
2232 ThrowException("Can't load from nonpointer type: " +
2233 (*$3)->getDescription());
2234 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2235 ThrowException("Can't load from pointer of non-first-class type: " +
2236 (*$3)->getDescription());
2237 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2240 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2241 const PointerType *PT = dyn_cast<PointerType>($5->get());
2243 ThrowException("Can't store to a nonpointer type: " +
2244 (*$5)->getDescription());
2245 const Type *ElTy = PT->getElementType();
2246 if (ElTy != $3->getType())
2247 ThrowException("Can't store '" + $3->getType()->getDescription() +
2248 "' into space of type '" + ElTy->getDescription() + "'!");
2250 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2253 | GETELEMENTPTR Types ValueRef IndexList {
2254 if (!isa<PointerType>($2->get()))
2255 ThrowException("getelementptr insn requires pointer operand!");
2257 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2258 // indices to uint struct indices for compatibility.
2259 generic_gep_type_iterator<std::vector<Value*>::iterator>
2260 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2261 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2262 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2263 if (isa<StructType>(*GTI)) // Only change struct indices
2264 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2265 if (CUI->getType() == Type::UByteTy)
2266 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2268 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2269 ThrowException("Invalid getelementptr indices for type '" +
2270 (*$2)->getDescription()+ "'!");
2271 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2272 delete $2; delete $4;
2277 int yyerror(const char *ErrorMsg) {
2279 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2280 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2281 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2282 if (yychar == YYEMPTY || yychar == 0)
2283 errMsg += "end-of-file.";
2285 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2286 ThrowException(errMsg);