1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Module.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iOperators.h"
21 #include "llvm/iPHINode.h"
22 #include "Support/STLExtras.h"
27 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
28 int yylex(); // declaration" of xxx warnings.
33 static Module *ParserResult;
34 std::string CurFilename;
36 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
37 // relating to upreferences in the input stream.
39 //#define DEBUG_UPREFS 1
41 #define UR_OUT(X) std::cerr << X
46 #define YYERROR_VERBOSE 1
48 // HACK ALERT: This variable is used to implement the automatic conversion of
49 // variable argument instructions from their old to new forms. When this
50 // compatiblity "Feature" is removed, this should be too.
52 static BasicBlock *CurBB;
53 static bool ObsoleteVarArgs;
56 // This contains info used when building the body of a function. It is
57 // destroyed when the function is completed.
59 typedef std::vector<Value *> ValueList; // Numbered defs
60 static void ResolveDefinitions(std::vector<ValueList> &LateResolvers,
61 std::vector<ValueList> *FutureLateResolvers = 0);
63 static struct PerModuleInfo {
64 Module *CurrentModule;
65 std::vector<ValueList> Values; // Module level numbered definitions
66 std::vector<ValueList> LateResolveValues;
67 std::vector<PATypeHolder> Types;
68 std::map<ValID, PATypeHolder> LateResolveTypes;
70 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
71 // references to global values. Global values may be referenced before they
72 // are defined, and if so, the temporary object that they represent is held
73 // here. This is used for forward references of ConstantPointerRefs.
75 typedef std::map<std::pair<const PointerType *,
76 ValID>, GlobalVariable*> GlobalRefsType;
77 GlobalRefsType GlobalRefs;
80 // If we could not resolve some functions at function compilation time
81 // (calls to functions before they are defined), resolve them now... Types
82 // are resolved when the constant pool has been completely parsed.
84 ResolveDefinitions(LateResolveValues);
86 // Check to make sure that all global value forward references have been
89 if (!GlobalRefs.empty()) {
90 std::string UndefinedReferences = "Unresolved global references exist:\n";
92 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
94 UndefinedReferences += " " + I->first.first->getDescription() + " " +
95 I->first.second.getName() + "\n";
97 ThrowException(UndefinedReferences);
100 Values.clear(); // Clear out function local definitions
106 // DeclareNewGlobalValue - Called every time a new GV has been defined. This
107 // is used to remove things from the forward declaration map, resolving them
108 // to the correct thing as needed.
110 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
111 // Check to see if there is a forward reference to this global variable...
112 // if there is, eliminate it and patch the reference to use the new def'n.
113 GlobalRefsType::iterator I =
114 GlobalRefs.find(std::make_pair(GV->getType(), D));
116 if (I != GlobalRefs.end()) {
117 GlobalVariable *OldGV = I->second; // Get the placeholder...
118 I->first.second.destroy(); // Free string memory if necessary
120 // Loop over all of the uses of the GlobalValue. The only thing they are
121 // allowed to be is ConstantPointerRef's.
122 assert(OldGV->hasOneUse() && "Only one reference should exist!");
123 User *U = OldGV->use_back(); // Must be a ConstantPointerRef...
124 ConstantPointerRef *CPR = cast<ConstantPointerRef>(U);
126 // Change the const pool reference to point to the real global variable
127 // now. This should drop a use from the OldGV.
128 CPR->mutateReferences(OldGV, GV);
129 assert(OldGV->use_empty() && "All uses should be gone now!");
131 // Remove OldGV from the module...
132 CurrentModule->getGlobalList().remove(OldGV);
133 delete OldGV; // Delete the old placeholder
135 // Remove the map entry for the global now that it has been created...
142 static struct PerFunctionInfo {
143 Function *CurrentFunction; // Pointer to current function being created
145 std::vector<ValueList> Values; // Keep track of numbered definitions
146 std::vector<ValueList> LateResolveValues;
147 std::vector<PATypeHolder> Types;
148 std::map<ValID, PATypeHolder> LateResolveTypes;
149 SymbolTable LocalSymtab;
150 bool isDeclare; // Is this function a forward declararation?
152 inline PerFunctionInfo() {
157 inline void FunctionStart(Function *M) {
161 void FunctionDone() {
162 // If we could not resolve some blocks at parsing time (forward branches)
163 // resolve the branches now...
164 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
166 // Make sure to resolve any constant expr references that might exist within
167 // the function we just declared itself.
169 if (CurrentFunction->hasName()) {
170 FID = ValID::create((char*)CurrentFunction->getName().c_str());
172 unsigned Slot = CurrentFunction->getType()->getUniqueID();
173 assert(CurModule.Values.size() > Slot && "Function not inserted?");
174 // Figure out which slot number if is...
175 for (unsigned i = 0; ; ++i) {
176 assert(i < CurModule.Values[Slot].size() && "Function not found!");
177 if (CurModule.Values[Slot][i] == CurrentFunction) {
178 FID = ValID::create((int)i);
183 CurModule.DeclareNewGlobalValue(CurrentFunction, FID);
185 Values.clear(); // Clear out function local definitions
186 Types.clear(); // Clear out function local types
187 LocalSymtab.clear(); // Clear out function local symbol table
191 } CurFun; // Info for the current function...
193 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
196 //===----------------------------------------------------------------------===//
197 // Code to handle definitions of all the types
198 //===----------------------------------------------------------------------===//
200 static int InsertValue(Value *D,
201 std::vector<ValueList> &ValueTab = CurFun.Values) {
202 if (D->hasName()) return -1; // Is this a numbered definition?
204 // Yes, insert the value into the value table...
205 unsigned type = D->getType()->getUniqueID();
206 if (ValueTab.size() <= type)
207 ValueTab.resize(type+1, ValueList());
208 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
209 ValueTab[type].push_back(D);
210 return ValueTab[type].size()-1;
213 // TODO: FIXME when Type are not const
214 static void InsertType(const Type *Ty, std::vector<PATypeHolder> &Types) {
218 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
220 case ValID::NumberVal: { // Is it a numbered definition?
221 unsigned Num = (unsigned)D.Num;
223 // Module constants occupy the lowest numbered slots...
224 if (Num < CurModule.Types.size())
225 return CurModule.Types[Num];
227 Num -= CurModule.Types.size();
229 // Check that the number is within bounds...
230 if (Num <= CurFun.Types.size())
231 return CurFun.Types[Num];
234 case ValID::NameVal: { // Is it a named definition?
235 std::string Name(D.Name);
236 SymbolTable *SymTab = 0;
238 if (inFunctionScope()) {
239 SymTab = &CurFun.CurrentFunction->getSymbolTable();
240 N = SymTab->lookup(Type::TypeTy, Name);
244 // Symbol table doesn't automatically chain yet... because the function
245 // hasn't been added to the module...
247 SymTab = &CurModule.CurrentModule->getSymbolTable();
248 N = SymTab->lookup(Type::TypeTy, Name);
252 D.destroy(); // Free old strdup'd memory...
253 return cast<Type>(N);
256 ThrowException("Internal parser error: Invalid symbol type reference!");
259 // If we reached here, we referenced either a symbol that we don't know about
260 // or an id number that hasn't been read yet. We may be referencing something
261 // forward, so just create an entry to be resolved later and get to it...
263 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
265 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
266 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
268 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
269 if (I != LateResolver.end()) {
273 Type *Typ = OpaqueType::get();
274 LateResolver.insert(std::make_pair(D, Typ));
278 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
279 SymbolTable &SymTab =
280 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
281 CurModule.CurrentModule->getSymbolTable();
282 return SymTab.lookup(Ty, Name);
285 // getValNonImprovising - Look up the value specified by the provided type and
286 // the provided ValID. If the value exists and has already been defined, return
287 // it. Otherwise return null.
289 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
290 if (isa<FunctionType>(Ty))
291 ThrowException("Functions are not values and "
292 "must be referenced as pointers");
295 case ValID::NumberVal: { // Is it a numbered definition?
296 unsigned type = Ty->getUniqueID();
297 unsigned Num = (unsigned)D.Num;
299 // Module constants occupy the lowest numbered slots...
300 if (type < CurModule.Values.size()) {
301 if (Num < CurModule.Values[type].size())
302 return CurModule.Values[type][Num];
304 Num -= CurModule.Values[type].size();
307 // Make sure that our type is within bounds
308 if (CurFun.Values.size() <= type) return 0;
310 // Check that the number is within bounds...
311 if (CurFun.Values[type].size() <= Num) return 0;
313 return CurFun.Values[type][Num];
316 case ValID::NameVal: { // Is it a named definition?
317 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
318 if (N == 0) return 0;
320 D.destroy(); // Free old strdup'd memory...
324 // Check to make sure that "Ty" is an integral type, and that our
325 // value will fit into the specified type...
326 case ValID::ConstSIntVal: // Is it a constant pool reference??
327 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
328 ThrowException("Signed integral constant '" +
329 itostr(D.ConstPool64) + "' is invalid for type '" +
330 Ty->getDescription() + "'!");
331 return ConstantSInt::get(Ty, D.ConstPool64);
333 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
334 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
335 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
336 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
337 "' is invalid or out of range!");
338 } else { // This is really a signed reference. Transmogrify.
339 return ConstantSInt::get(Ty, D.ConstPool64);
342 return ConstantUInt::get(Ty, D.UConstPool64);
345 case ValID::ConstFPVal: // Is it a floating point const pool reference?
346 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
347 ThrowException("FP constant invalid for type!!");
348 return ConstantFP::get(Ty, D.ConstPoolFP);
350 case ValID::ConstNullVal: // Is it a null value?
351 if (!isa<PointerType>(Ty))
352 ThrowException("Cannot create a a non pointer null!");
353 return ConstantPointerNull::get(cast<PointerType>(Ty));
355 case ValID::ConstantVal: // Fully resolved constant?
356 if (D.ConstantValue->getType() != Ty)
357 ThrowException("Constant expression type different from required type!");
358 return D.ConstantValue;
361 assert(0 && "Unhandled case!");
365 assert(0 && "Unhandled case!");
370 // getVal - This function is identical to getValNonImprovising, except that if a
371 // value is not already defined, it "improvises" by creating a placeholder var
372 // that looks and acts just like the requested variable. When the value is
373 // defined later, all uses of the placeholder variable are replaced with the
376 static Value *getVal(const Type *Ty, const ValID &D) {
377 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
379 // See if the value has already been defined...
380 Value *V = getValNonImprovising(Ty, D);
383 // If we reached here, we referenced either a symbol that we don't know about
384 // or an id number that hasn't been read yet. We may be referencing something
385 // forward, so just create an entry to be resolved later and get to it...
388 switch (Ty->getPrimitiveID()) {
389 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
390 default: d = new ValuePlaceHolder(Ty, D); break;
393 assert(d != 0 && "How did we not make something?");
394 if (inFunctionScope())
395 InsertValue(d, CurFun.LateResolveValues);
397 InsertValue(d, CurModule.LateResolveValues);
402 //===----------------------------------------------------------------------===//
403 // Code to handle forward references in instructions
404 //===----------------------------------------------------------------------===//
406 // This code handles the late binding needed with statements that reference
407 // values not defined yet... for example, a forward branch, or the PHI node for
410 // This keeps a table (CurFun.LateResolveValues) of all such forward references
411 // and back patchs after we are done.
414 // ResolveDefinitions - If we could not resolve some defs at parsing
415 // time (forward branches, phi functions for loops, etc...) resolve the
418 static void ResolveDefinitions(std::vector<ValueList> &LateResolvers,
419 std::vector<ValueList> *FutureLateResolvers) {
420 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
421 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
422 while (!LateResolvers[ty].empty()) {
423 Value *V = LateResolvers[ty].back();
424 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
426 LateResolvers[ty].pop_back();
427 ValID &DID = getValIDFromPlaceHolder(V);
429 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
431 V->replaceAllUsesWith(TheRealValue);
433 } else if (FutureLateResolvers) {
434 // Functions have their unresolved items forwarded to the module late
436 InsertValue(V, *FutureLateResolvers);
438 if (DID.Type == ValID::NameVal)
439 ThrowException("Reference to an invalid definition: '" +DID.getName()+
440 "' of type '" + V->getType()->getDescription() + "'",
441 getLineNumFromPlaceHolder(V));
443 ThrowException("Reference to an invalid definition: #" +
444 itostr(DID.Num) + " of type '" +
445 V->getType()->getDescription() + "'",
446 getLineNumFromPlaceHolder(V));
451 LateResolvers.clear();
454 // ResolveTypeTo - A brand new type was just declared. This means that (if
455 // name is not null) things referencing Name can be resolved. Otherwise, things
456 // refering to the number can be resolved. Do this now.
458 static void ResolveTypeTo(char *Name, const Type *ToTy) {
459 std::vector<PATypeHolder> &Types = inFunctionScope() ?
460 CurFun.Types : CurModule.Types;
463 if (Name) D = ValID::create(Name);
464 else D = ValID::create((int)Types.size());
466 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
467 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
469 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
470 if (I != LateResolver.end()) {
471 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
472 LateResolver.erase(I);
476 // ResolveTypes - At this point, all types should be resolved. Any that aren't
479 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
480 if (!LateResolveTypes.empty()) {
481 const ValID &DID = LateResolveTypes.begin()->first;
483 if (DID.Type == ValID::NameVal)
484 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
486 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
491 // setValueName - Set the specified value to the name given. The name may be
492 // null potentially, in which case this is a noop. The string passed in is
493 // assumed to be a malloc'd string buffer, and is freed by this function.
495 // This function returns true if the value has already been defined, but is
496 // allowed to be redefined in the specified context. If the name is a new name
497 // for the typeplane, false is returned.
499 static bool setValueName(Value *V, char *NameStr) {
500 if (NameStr == 0) return false;
502 std::string Name(NameStr); // Copy string
503 free(NameStr); // Free old string
505 if (V->getType() == Type::VoidTy)
506 ThrowException("Can't assign name '" + Name +
507 "' to a null valued instruction!");
509 SymbolTable &ST = inFunctionScope() ?
510 CurFun.CurrentFunction->getSymbolTable() :
511 CurModule.CurrentModule->getSymbolTable();
513 Value *Existing = ST.lookup(V->getType(), Name);
514 if (Existing) { // Inserting a name that is already defined???
515 // There is only one case where this is allowed: when we are refining an
516 // opaque type. In this case, Existing will be an opaque type.
517 if (const Type *Ty = dyn_cast<Type>(Existing)) {
518 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
519 // We ARE replacing an opaque type!
520 ((OpaqueType*)OpTy)->refineAbstractTypeTo(cast<Type>(V));
525 // Otherwise, we are a simple redefinition of a value, check to see if it
526 // is defined the same as the old one...
527 if (const Type *Ty = dyn_cast<Type>(Existing)) {
528 if (Ty == cast<Type>(V)) return true; // Yes, it's equal.
529 // std::cerr << "Type: " << Ty->getDescription() << " != "
530 // << cast<Type>(V)->getDescription() << "!\n";
531 } else if (const Constant *C = dyn_cast<Constant>(Existing)) {
532 if (C == V) return true; // Constants are equal to themselves
533 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
534 // We are allowed to redefine a global variable in two circumstances:
535 // 1. If at least one of the globals is uninitialized or
536 // 2. If both initializers have the same value.
538 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
539 if (!EGV->hasInitializer() || !GV->hasInitializer() ||
540 EGV->getInitializer() == GV->getInitializer()) {
542 // Make sure the existing global version gets the initializer! Make
543 // sure that it also gets marked const if the new version is.
544 if (GV->hasInitializer() && !EGV->hasInitializer())
545 EGV->setInitializer(GV->getInitializer());
546 if (GV->isConstant())
547 EGV->setConstant(true);
548 EGV->setLinkage(GV->getLinkage());
550 delete GV; // Destroy the duplicate!
551 return true; // They are equivalent!
556 ThrowException("Redefinition of value named '" + Name + "' in the '" +
557 V->getType()->getDescription() + "' type plane!");
561 V->setName(Name, &ST);
563 // If we're in function scope
564 if (inFunctionScope()) {
565 // Look up the symbol in the function's local symboltable
566 Existing = CurFun.LocalSymtab.lookup(V->getType(),Name);
568 // If it already exists
571 ThrowException("Redefinition of value named '" + Name + "' in the '" +
572 V->getType()->getDescription() + "' type plane!");
574 // otherwise, since it doesn't exist
577 CurFun.LocalSymtab.insert(V);
584 //===----------------------------------------------------------------------===//
585 // Code for handling upreferences in type names...
588 // TypeContains - Returns true if Ty directly contains E in it.
590 static bool TypeContains(const Type *Ty, const Type *E) {
591 return find(Ty->subtype_begin(), Ty->subtype_end(), E) != Ty->subtype_end();
596 // NestingLevel - The number of nesting levels that need to be popped before
597 // this type is resolved.
598 unsigned NestingLevel;
600 // LastContainedTy - This is the type at the current binding level for the
601 // type. Every time we reduce the nesting level, this gets updated.
602 const Type *LastContainedTy;
604 // UpRefTy - This is the actual opaque type that the upreference is
608 UpRefRecord(unsigned NL, OpaqueType *URTy)
609 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
613 // UpRefs - A list of the outstanding upreferences that need to be resolved.
614 static std::vector<UpRefRecord> UpRefs;
616 /// HandleUpRefs - Every time we finish a new layer of types, this function is
617 /// called. It loops through the UpRefs vector, which is a list of the
618 /// currently active types. For each type, if the up reference is contained in
619 /// the newly completed type, we decrement the level count. When the level
620 /// count reaches zero, the upreferenced type is the type that is passed in:
621 /// thus we can complete the cycle.
623 static PATypeHolder HandleUpRefs(const Type *ty) {
624 if (!ty->isAbstract()) return ty;
626 UR_OUT("Type '" << Ty->getDescription() <<
627 "' newly formed. Resolving upreferences.\n" <<
628 UpRefs.size() << " upreferences active!\n");
630 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
631 // to zero), we resolve them all together before we resolve them to Ty. At
632 // the end of the loop, if there is anything to resolve to Ty, it will be in
634 OpaqueType *TypeToResolve = 0;
636 for (unsigned i = 0; i != UpRefs.size(); ++i) {
637 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
638 << UpRefs[i].second->getDescription() << ") = "
639 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
640 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
641 // Decrement level of upreference
642 unsigned Level = --UpRefs[i].NestingLevel;
643 UpRefs[i].LastContainedTy = Ty;
644 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
645 if (Level == 0) { // Upreference should be resolved!
646 if (!TypeToResolve) {
647 TypeToResolve = UpRefs[i].UpRefTy;
649 UR_OUT(" * Resolving upreference for "
650 << UpRefs[i].second->getDescription() << "\n";
651 std::string OldName = UpRefs[i].UpRefTy->getDescription());
652 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
653 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
654 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
656 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
657 --i; // Do not skip the next element...
663 UR_OUT(" * Resolving upreference for "
664 << UpRefs[i].second->getDescription() << "\n";
665 std::string OldName = UpRefs[i].UpRefTy->getDescription());
666 TypeToResolve->refineAbstractTypeTo(Ty);
673 //===----------------------------------------------------------------------===//
674 // RunVMAsmParser - Define an interface to this parser
675 //===----------------------------------------------------------------------===//
677 Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
679 CurFilename = Filename;
680 llvmAsmlineno = 1; // Reset the current line number...
681 ObsoleteVarArgs = false;
683 // Allocate a new module to read
684 CurModule.CurrentModule = new Module(Filename);
687 yyparse(); // Parse the file.
689 // Clear the symbol table so it doesn't complain when it
691 CurFun.LocalSymtab.clear();
695 Module *Result = ParserResult;
697 // Check to see if they called va_start but not va_arg..
698 if (!ObsoleteVarArgs)
699 if (Function *F = Result->getNamedFunction("llvm.va_start"))
700 if (F->asize() == 1) {
701 std::cerr << "WARNING: this file uses obsolete features. "
702 << "Assemble and disassemble to update it.\n";
703 ObsoleteVarArgs = true;
707 if (ObsoleteVarArgs) {
708 // If the user is making use of obsolete varargs intrinsics, adjust them for
710 if (Function *F = Result->getNamedFunction("llvm.va_start")) {
711 assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
713 const Type *RetTy = F->getFunctionType()->getParamType(0);
714 RetTy = cast<PointerType>(RetTy)->getElementType();
715 Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
717 while (!F->use_empty()) {
718 CallInst *CI = cast<CallInst>(F->use_back());
719 Value *V = new CallInst(NF, "", CI);
720 new StoreInst(V, CI->getOperand(1), CI);
721 CI->getParent()->getInstList().erase(CI);
723 Result->getFunctionList().erase(F);
726 if (Function *F = Result->getNamedFunction("llvm.va_end")) {
727 assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
728 const Type *ArgTy = F->getFunctionType()->getParamType(0);
729 ArgTy = cast<PointerType>(ArgTy)->getElementType();
730 Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
733 while (!F->use_empty()) {
734 CallInst *CI = cast<CallInst>(F->use_back());
735 Value *V = new LoadInst(CI->getOperand(1), "", CI);
736 new CallInst(NF, V, "", CI);
737 CI->getParent()->getInstList().erase(CI);
739 Result->getFunctionList().erase(F);
742 if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
743 assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
744 const Type *ArgTy = F->getFunctionType()->getParamType(0);
745 ArgTy = cast<PointerType>(ArgTy)->getElementType();
746 Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
749 while (!F->use_empty()) {
750 CallInst *CI = cast<CallInst>(F->use_back());
751 Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
752 new StoreInst(V, CI->getOperand(1), CI);
753 CI->getParent()->getInstList().erase(CI);
755 Result->getFunctionList().erase(F);
759 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
765 } // End llvm namespace
767 using namespace llvm;
772 llvm::Module *ModuleVal;
773 llvm::Function *FunctionVal;
774 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
775 llvm::BasicBlock *BasicBlockVal;
776 llvm::TerminatorInst *TermInstVal;
777 llvm::Instruction *InstVal;
778 llvm::Constant *ConstVal;
780 const llvm::Type *PrimType;
781 llvm::PATypeHolder *TypeVal;
782 llvm::Value *ValueVal;
784 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
785 std::vector<llvm::Value*> *ValueList;
786 std::list<llvm::PATypeHolder> *TypeList;
787 std::list<std::pair<llvm::Value*,
788 llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
789 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
790 std::vector<llvm::Constant*> *ConstVector;
792 llvm::GlobalValue::LinkageTypes Linkage;
800 char *StrVal; // This memory is strdup'd!
801 llvm::ValID ValIDVal; // strdup'd memory maybe!
803 llvm::Instruction::BinaryOps BinaryOpVal;
804 llvm::Instruction::TermOps TermOpVal;
805 llvm::Instruction::MemoryOps MemOpVal;
806 llvm::Instruction::OtherOps OtherOpVal;
807 llvm::Module::Endianness Endianness;
810 %type <ModuleVal> Module FunctionList
811 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
812 %type <BasicBlockVal> BasicBlock InstructionList
813 %type <TermInstVal> BBTerminatorInst
814 %type <InstVal> Inst InstVal MemoryInst
815 %type <ConstVal> ConstVal ConstExpr
816 %type <ConstVector> ConstVector
817 %type <ArgList> ArgList ArgListH
818 %type <ArgVal> ArgVal
819 %type <PHIList> PHIList
820 %type <ValueList> ValueRefList ValueRefListE // For call param lists
821 %type <ValueList> IndexList // For GEP derived indices
822 %type <TypeList> TypeListI ArgTypeListI
823 %type <JumpTable> JumpTable
824 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
825 %type <BoolVal> OptVolatile // 'volatile' or not
826 %type <Linkage> OptLinkage
827 %type <Endianness> BigOrLittle
829 // ValueRef - Unresolved reference to a definition or BB
830 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
831 %type <ValueVal> ResolvedVal // <type> <valref> pair
832 // Tokens and types for handling constant integer values
834 // ESINT64VAL - A negative number within long long range
835 %token <SInt64Val> ESINT64VAL
837 // EUINT64VAL - A positive number within uns. long long range
838 %token <UInt64Val> EUINT64VAL
839 %type <SInt64Val> EINT64VAL
841 %token <SIntVal> SINTVAL // Signed 32 bit ints...
842 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
843 %type <SIntVal> INTVAL
844 %token <FPVal> FPVAL // Float or Double constant
847 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
848 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
849 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
850 %token <PrimType> FLOAT DOUBLE TYPE LABEL
852 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
853 %type <StrVal> Name OptName OptAssign
856 %token IMPLEMENTATION ZEROINITIALIZER TRUE FALSE BEGINTOK ENDTOK
857 %token DECLARE GLOBAL CONSTANT VOLATILE
858 %token TO DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE WEAK APPENDING
859 %token OPAQUE NOT EXTERNAL TARGET ENDIAN POINTERSIZE LITTLE BIG
861 // Basic Block Terminating Operators
862 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND
865 %type <BinaryOpVal> BinaryOps // all the binary operators
866 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
867 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
868 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
870 // Memory Instructions
871 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
874 %type <OtherOpVal> ShiftOps
875 %token <OtherOpVal> PHI_TOK CALL CAST SHL SHR VAARG VANEXT
876 %token VA_ARG // FIXME: OBSOLETE
881 // Handle constant integer size restriction and conversion...
885 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
886 ThrowException("Value too large for type!");
891 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
892 EINT64VAL : EUINT64VAL {
893 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
894 ThrowException("Value too large for type!");
898 // Operations that are notably excluded from this list include:
899 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
901 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
902 LogicalOps : AND | OR | XOR;
903 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
904 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
906 ShiftOps : SHL | SHR;
908 // These are some types that allow classification if we only want a particular
909 // thing... for example, only a signed, unsigned, or integral type.
910 SIntType : LONG | INT | SHORT | SBYTE;
911 UIntType : ULONG | UINT | USHORT | UBYTE;
912 IntType : SIntType | UIntType;
913 FPType : FLOAT | DOUBLE;
915 // OptAssign - Value producing statements have an optional assignment component
916 OptAssign : Name '=' {
923 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
924 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
925 WEAK { $$ = GlobalValue::WeakLinkage; } |
926 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
927 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
929 //===----------------------------------------------------------------------===//
930 // Types includes all predefined types... except void, because it can only be
931 // used in specific contexts (function returning void for example). To have
932 // access to it, a user must explicitly use TypesV.
935 // TypesV includes all of 'Types', but it also includes the void type.
936 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
937 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
941 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
946 // Derived types are added later...
948 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
949 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
951 $$ = new PATypeHolder(OpaqueType::get());
954 $$ = new PATypeHolder($1);
956 UpRTypes : SymbolicValueRef { // Named types are also simple types...
957 $$ = new PATypeHolder(getTypeVal($1));
960 // Include derived types in the Types production.
962 UpRTypes : '\\' EUINT64VAL { // Type UpReference
963 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
964 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
965 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
966 $$ = new PATypeHolder(OT);
967 UR_OUT("New Upreference!\n");
969 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
970 std::vector<const Type*> Params;
971 mapto($3->begin(), $3->end(), std::back_inserter(Params),
972 std::mem_fun_ref(&PATypeHolder::get));
973 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
974 if (isVarArg) Params.pop_back();
976 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
977 delete $3; // Delete the argument list
978 delete $1; // Delete the return type handle
980 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
981 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
984 | '{' TypeListI '}' { // Structure type?
985 std::vector<const Type*> Elements;
986 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
987 std::mem_fun_ref(&PATypeHolder::get));
989 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
992 | '{' '}' { // Empty structure type?
993 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
995 | UpRTypes '*' { // Pointer type?
996 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1000 // TypeList - Used for struct declarations and as a basis for function type
1001 // declaration type lists
1003 TypeListI : UpRTypes {
1004 $$ = new std::list<PATypeHolder>();
1005 $$->push_back(*$1); delete $1;
1007 | TypeListI ',' UpRTypes {
1008 ($$=$1)->push_back(*$3); delete $3;
1011 // ArgTypeList - List of types for a function type declaration...
1012 ArgTypeListI : TypeListI
1013 | TypeListI ',' DOTDOTDOT {
1014 ($$=$1)->push_back(Type::VoidTy);
1017 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1020 $$ = new std::list<PATypeHolder>();
1023 // ConstVal - The various declarations that go into the constant pool. This
1024 // production is used ONLY to represent constants that show up AFTER a 'const',
1025 // 'constant' or 'global' token at global scope. Constants that can be inlined
1026 // into other expressions (such as integers and constexprs) are handled by the
1027 // ResolvedVal, ValueRef and ConstValueRef productions.
1029 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1030 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1032 ThrowException("Cannot make array constant with type: '" +
1033 (*$1)->getDescription() + "'!");
1034 const Type *ETy = ATy->getElementType();
1035 int NumElements = ATy->getNumElements();
1037 // Verify that we have the correct size...
1038 if (NumElements != -1 && NumElements != (int)$3->size())
1039 ThrowException("Type mismatch: constant sized array initialized with " +
1040 utostr($3->size()) + " arguments, but has size of " +
1041 itostr(NumElements) + "!");
1043 // Verify all elements are correct type!
1044 for (unsigned i = 0; i < $3->size(); i++) {
1045 if (ETy != (*$3)[i]->getType())
1046 ThrowException("Element #" + utostr(i) + " is not of type '" +
1047 ETy->getDescription() +"' as required!\nIt is of type '"+
1048 (*$3)[i]->getType()->getDescription() + "'.");
1051 $$ = ConstantArray::get(ATy, *$3);
1052 delete $1; delete $3;
1055 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1057 ThrowException("Cannot make array constant with type: '" +
1058 (*$1)->getDescription() + "'!");
1060 int NumElements = ATy->getNumElements();
1061 if (NumElements != -1 && NumElements != 0)
1062 ThrowException("Type mismatch: constant sized array initialized with 0"
1063 " arguments, but has size of " + itostr(NumElements) +"!");
1064 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1067 | Types 'c' STRINGCONSTANT {
1068 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1070 ThrowException("Cannot make array constant with type: '" +
1071 (*$1)->getDescription() + "'!");
1073 int NumElements = ATy->getNumElements();
1074 const Type *ETy = ATy->getElementType();
1075 char *EndStr = UnEscapeLexed($3, true);
1076 if (NumElements != -1 && NumElements != (EndStr-$3))
1077 ThrowException("Can't build string constant of size " +
1078 itostr((int)(EndStr-$3)) +
1079 " when array has size " + itostr(NumElements) + "!");
1080 std::vector<Constant*> Vals;
1081 if (ETy == Type::SByteTy) {
1082 for (char *C = $3; C != EndStr; ++C)
1083 Vals.push_back(ConstantSInt::get(ETy, *C));
1084 } else if (ETy == Type::UByteTy) {
1085 for (char *C = $3; C != EndStr; ++C)
1086 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1089 ThrowException("Cannot build string arrays of non byte sized elements!");
1092 $$ = ConstantArray::get(ATy, Vals);
1095 | Types '{' ConstVector '}' {
1096 const StructType *STy = dyn_cast<StructType>($1->get());
1098 ThrowException("Cannot make struct constant with type: '" +
1099 (*$1)->getDescription() + "'!");
1101 if ($3->size() != STy->getNumContainedTypes())
1102 ThrowException("Illegal number of initializers for structure type!");
1104 // Check to ensure that constants are compatible with the type initializer!
1105 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1106 if ((*$3)[i]->getType() != STy->getElementType(i))
1107 ThrowException("Expected type '" +
1108 STy->getElementType(i)->getDescription() +
1109 "' for element #" + utostr(i) +
1110 " of structure initializer!");
1112 $$ = ConstantStruct::get(STy, *$3);
1113 delete $1; delete $3;
1116 const StructType *STy = dyn_cast<StructType>($1->get());
1118 ThrowException("Cannot make struct constant with type: '" +
1119 (*$1)->getDescription() + "'!");
1121 if (STy->getNumContainedTypes() != 0)
1122 ThrowException("Illegal number of initializers for structure type!");
1124 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1128 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1130 ThrowException("Cannot make null pointer constant with type: '" +
1131 (*$1)->getDescription() + "'!");
1133 $$ = ConstantPointerNull::get(PTy);
1136 | Types SymbolicValueRef {
1137 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1139 ThrowException("Global const reference must be a pointer type!");
1141 // ConstExprs can exist in the body of a function, thus creating
1142 // ConstantPointerRefs whenever they refer to a variable. Because we are in
1143 // the context of a function, getValNonImprovising will search the functions
1144 // symbol table instead of the module symbol table for the global symbol,
1145 // which throws things all off. To get around this, we just tell
1146 // getValNonImprovising that we are at global scope here.
1148 Function *SavedCurFn = CurFun.CurrentFunction;
1149 CurFun.CurrentFunction = 0;
1151 Value *V = getValNonImprovising(Ty, $2);
1153 CurFun.CurrentFunction = SavedCurFn;
1155 // If this is an initializer for a constant pointer, which is referencing a
1156 // (currently) undefined variable, create a stub now that shall be replaced
1157 // in the future with the right type of variable.
1160 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1161 const PointerType *PT = cast<PointerType>(Ty);
1163 // First check to see if the forward references value is already created!
1164 PerModuleInfo::GlobalRefsType::iterator I =
1165 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1167 if (I != CurModule.GlobalRefs.end()) {
1168 V = I->second; // Placeholder already exists, use it...
1171 // Create a placeholder for the global variable reference...
1172 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
1174 GlobalValue::ExternalLinkage);
1175 // Keep track of the fact that we have a forward ref to recycle it
1176 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1178 // Must temporarily push this value into the module table...
1179 CurModule.CurrentModule->getGlobalList().push_back(GV);
1184 GlobalValue *GV = cast<GlobalValue>(V);
1185 $$ = ConstantPointerRef::get(GV);
1186 delete $1; // Free the type handle
1189 if ($1->get() != $2->getType())
1190 ThrowException("Mismatched types for constant expression!");
1194 | Types ZEROINITIALIZER {
1195 $$ = Constant::getNullValue($1->get());
1199 ConstVal : SIntType EINT64VAL { // integral constants
1200 if (!ConstantSInt::isValueValidForType($1, $2))
1201 ThrowException("Constant value doesn't fit in type!");
1202 $$ = ConstantSInt::get($1, $2);
1204 | UIntType EUINT64VAL { // integral constants
1205 if (!ConstantUInt::isValueValidForType($1, $2))
1206 ThrowException("Constant value doesn't fit in type!");
1207 $$ = ConstantUInt::get($1, $2);
1209 | BOOL TRUE { // Boolean constants
1210 $$ = ConstantBool::True;
1212 | BOOL FALSE { // Boolean constants
1213 $$ = ConstantBool::False;
1215 | FPType FPVAL { // Float & Double constants
1216 $$ = ConstantFP::get($1, $2);
1220 ConstExpr: CAST '(' ConstVal TO Types ')' {
1221 if (!$3->getType()->isFirstClassType())
1222 ThrowException("cast constant expression from a non-primitive type: '" +
1223 $3->getType()->getDescription() + "'!");
1224 if (!$5->get()->isFirstClassType())
1225 ThrowException("cast constant expression to a non-primitive type: '" +
1226 $5->get()->getDescription() + "'!");
1227 $$ = ConstantExpr::getCast($3, $5->get());
1230 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1231 if (!isa<PointerType>($3->getType()))
1232 ThrowException("GetElementPtr requires a pointer operand!");
1235 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1237 ThrowException("Index list invalid for constant getelementptr!");
1239 std::vector<Constant*> IdxVec;
1240 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1241 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1242 IdxVec.push_back(C);
1244 ThrowException("Indices to constant getelementptr must be constants!");
1248 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1250 | BinaryOps '(' ConstVal ',' ConstVal ')' {
1251 if ($3->getType() != $5->getType())
1252 ThrowException("Binary operator types must match!");
1253 $$ = ConstantExpr::get($1, $3, $5);
1255 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1256 if ($5->getType() != Type::UByteTy)
1257 ThrowException("Shift count for shift constant must be unsigned byte!");
1258 if (!$3->getType()->isInteger())
1259 ThrowException("Shift constant expression requires integer operand!");
1260 $$ = ConstantExpr::get($1, $3, $5);
1264 // ConstVector - A list of comma separated constants.
1265 ConstVector : ConstVector ',' ConstVal {
1266 ($$ = $1)->push_back($3);
1269 $$ = new std::vector<Constant*>();
1274 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1275 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1278 //===----------------------------------------------------------------------===//
1279 // Rules to match Modules
1280 //===----------------------------------------------------------------------===//
1282 // Module rule: Capture the result of parsing the whole file into a result
1285 Module : FunctionList {
1286 $$ = ParserResult = $1;
1287 CurModule.ModuleDone();
1290 // FunctionList - A list of functions, preceeded by a constant pool.
1292 FunctionList : FunctionList Function {
1294 assert($2->getParent() == 0 && "Function already in module!");
1295 $1->getFunctionList().push_back($2);
1296 CurFun.FunctionDone();
1298 | FunctionList FunctionProto {
1301 | FunctionList IMPLEMENTATION {
1305 $$ = CurModule.CurrentModule;
1306 // Resolve circular types before we parse the body of the module
1307 ResolveTypes(CurModule.LateResolveTypes);
1310 // ConstPool - Constants with optional names assigned to them.
1311 ConstPool : ConstPool OptAssign CONST ConstVal {
1312 if (!setValueName($4, $2))
1315 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1316 // Eagerly resolve types. This is not an optimization, this is a
1317 // requirement that is due to the fact that we could have this:
1319 // %list = type { %list * }
1320 // %list = type { %list * } ; repeated type decl
1322 // If types are not resolved eagerly, then the two types will not be
1323 // determined to be the same type!
1325 ResolveTypeTo($2, $4->get());
1327 // TODO: FIXME when Type are not const
1328 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1329 // If this is not a redefinition of a type...
1331 InsertType($4->get(),
1332 inFunctionScope() ? CurFun.Types : CurModule.Types);
1338 | ConstPool FunctionProto { // Function prototypes can be in const pool
1340 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1341 const Type *Ty = $5->getType();
1342 // Global declarations appear in Constant Pool
1343 Constant *Initializer = $5;
1344 if (Initializer == 0)
1345 ThrowException("Global value initializer is not a constant!");
1347 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1348 if (!setValueName(GV, $2)) { // If not redefining...
1349 CurModule.CurrentModule->getGlobalList().push_back(GV);
1350 int Slot = InsertValue(GV, CurModule.Values);
1353 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1355 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1356 (char*)GV->getName().c_str()));
1360 | ConstPool OptAssign EXTERNAL GlobalType Types {
1361 const Type *Ty = *$5;
1362 // Global declarations appear in Constant Pool
1363 GlobalVariable *GV = new GlobalVariable(Ty,$4,GlobalValue::ExternalLinkage);
1364 if (!setValueName(GV, $2)) { // If not redefining...
1365 CurModule.CurrentModule->getGlobalList().push_back(GV);
1366 int Slot = InsertValue(GV, CurModule.Values);
1369 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1371 assert(GV->hasName() && "Not named and not numbered!?");
1372 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1373 (char*)GV->getName().c_str()));
1378 | ConstPool TARGET TargetDefinition {
1380 | /* empty: end of list */ {
1385 BigOrLittle : BIG { $$ = Module::BigEndian; };
1386 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1388 TargetDefinition : ENDIAN '=' BigOrLittle {
1389 CurModule.CurrentModule->setEndianness($3);
1391 | POINTERSIZE '=' EUINT64VAL {
1393 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1395 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1397 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1401 //===----------------------------------------------------------------------===//
1402 // Rules to match Function Headers
1403 //===----------------------------------------------------------------------===//
1405 Name : VAR_ID | STRINGCONSTANT;
1406 OptName : Name | /*empty*/ { $$ = 0; };
1408 ArgVal : Types OptName {
1409 if (*$1 == Type::VoidTy)
1410 ThrowException("void typed arguments are invalid!");
1411 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1414 ArgListH : ArgListH ',' ArgVal {
1420 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1425 ArgList : ArgListH {
1428 | ArgListH ',' DOTDOTDOT {
1430 $$->push_back(std::pair<PATypeHolder*,
1431 char*>(new PATypeHolder(Type::VoidTy), 0));
1434 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1435 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1441 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1443 std::string FunctionName($2);
1445 if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1446 ThrowException("LLVM functions cannot return aggregate types!");
1448 std::vector<const Type*> ParamTypeList;
1449 if ($4) { // If there are arguments...
1450 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1451 I != $4->end(); ++I)
1452 ParamTypeList.push_back(I->first->get());
1455 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1456 if (isVarArg) ParamTypeList.pop_back();
1458 const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1459 const PointerType *PFT = PointerType::get(FT);
1463 // Is the function already in symtab?
1464 if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1465 // Yes it is. If this is the case, either we need to be a forward decl,
1466 // or it needs to be.
1467 if (!CurFun.isDeclare && !Fn->isExternal())
1468 ThrowException("Redefinition of function '" + FunctionName + "'!");
1470 // If we found a preexisting function prototype, remove it from the
1471 // module, so that we don't get spurious conflicts with global & local
1474 CurModule.CurrentModule->getFunctionList().remove(Fn);
1476 // Make sure to strip off any argument names so we can't get conflicts...
1477 for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1480 } else { // Not already defined?
1481 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName);
1482 InsertValue(Fn, CurModule.Values);
1483 CurModule.DeclareNewGlobalValue(Fn, ValID::create($2));
1485 free($2); // Free strdup'd memory!
1487 CurFun.FunctionStart(Fn);
1489 // Add all of the arguments we parsed to the function...
1490 if ($4) { // Is null if empty...
1491 if (isVarArg) { // Nuke the last entry
1492 assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1493 "Not a varargs marker!");
1494 delete $4->back().first;
1495 $4->pop_back(); // Delete the last entry
1497 Function::aiterator ArgIt = Fn->abegin();
1498 for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1499 I != $4->end(); ++I, ++ArgIt) {
1500 delete I->first; // Delete the typeholder...
1502 if (setValueName(ArgIt, I->second)) // Insert arg into symtab...
1503 assert(0 && "No arg redef allowed!");
1508 delete $4; // We're now done with the argument list
1512 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1514 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1515 $$ = CurFun.CurrentFunction;
1517 // Make sure that we keep track of the linkage type even if there was a
1518 // previous "declare".
1521 // Resolve circular types before we parse the body of the function.
1522 ResolveTypes(CurFun.LateResolveTypes);
1525 END : ENDTOK | '}'; // Allow end of '}' to end a function
1527 Function : BasicBlockList END {
1531 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1532 $$ = CurFun.CurrentFunction;
1533 assert($$->getParent() == 0 && "Function already in module!");
1534 CurModule.CurrentModule->getFunctionList().push_back($$);
1535 CurFun.FunctionDone();
1538 //===----------------------------------------------------------------------===//
1539 // Rules to match Basic Blocks
1540 //===----------------------------------------------------------------------===//
1542 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1543 $$ = ValID::create($1);
1546 $$ = ValID::create($1);
1548 | FPVAL { // Perhaps it's an FP constant?
1549 $$ = ValID::create($1);
1552 $$ = ValID::create(ConstantBool::True);
1555 $$ = ValID::create(ConstantBool::False);
1558 $$ = ValID::createNull();
1561 $$ = ValID::create($1);
1564 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1567 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1568 $$ = ValID::create($1);
1570 | Name { // Is it a named reference...?
1571 $$ = ValID::create($1);
1574 // ValueRef - A reference to a definition... either constant or symbolic
1575 ValueRef : SymbolicValueRef | ConstValueRef;
1578 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1579 // type immediately preceeds the value reference, and allows complex constant
1580 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1581 ResolvedVal : Types ValueRef {
1582 $$ = getVal(*$1, $2); delete $1;
1585 BasicBlockList : BasicBlockList BasicBlock {
1586 ($$ = $1)->getBasicBlockList().push_back($2);
1588 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1589 ($$ = $1)->getBasicBlockList().push_back($2);
1593 // Basic blocks are terminated by branching instructions:
1594 // br, br/cc, switch, ret
1596 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1597 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1600 $1->getInstList().push_back($3);
1604 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1605 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1608 $2->getInstList().push_back($4);
1609 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1615 InstructionList : InstructionList Inst {
1616 $1->getInstList().push_back($2);
1620 $$ = CurBB = new BasicBlock();
1623 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1624 $$ = new ReturnInst($2);
1626 | RET VOID { // Return with no result...
1627 $$ = new ReturnInst();
1629 | BR LABEL ValueRef { // Unconditional Branch...
1630 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1631 } // Conditional Branch...
1632 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1633 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1634 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1635 getVal(Type::BoolTy, $3));
1637 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1638 SwitchInst *S = new SwitchInst(getVal($2, $3),
1639 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1642 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1645 S->addCase(I->first, I->second);
1647 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1648 SwitchInst *S = new SwitchInst(getVal($2, $3),
1649 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1652 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1653 UNWIND ResolvedVal {
1654 const PointerType *PFTy;
1655 const FunctionType *Ty;
1657 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1658 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1659 // Pull out the types of all of the arguments...
1660 std::vector<const Type*> ParamTypes;
1662 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1664 ParamTypes.push_back((*I)->getType());
1667 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1668 if (isVarArg) ParamTypes.pop_back();
1670 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1671 PFTy = PointerType::get(Ty);
1674 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1676 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1677 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1679 if (Normal == 0 || Except == 0)
1680 ThrowException("Invoke instruction without label destinations!");
1682 // Create the call node...
1683 if (!$5) { // Has no arguments?
1684 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1685 } else { // Has arguments?
1686 // Loop through FunctionType's arguments and ensure they are specified
1689 FunctionType::param_iterator I = Ty->param_begin();
1690 FunctionType::param_iterator E = Ty->param_end();
1691 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1693 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1694 if ((*ArgI)->getType() != *I)
1695 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1696 (*I)->getDescription() + "'!");
1698 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1699 ThrowException("Invalid number of parameters detected!");
1701 $$ = new InvokeInst(V, Normal, Except, *$5);
1707 $$ = new UnwindInst();
1712 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1714 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1716 ThrowException("May only switch on a constant pool value!");
1718 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1720 | IntType ConstValueRef ',' LABEL ValueRef {
1721 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1722 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1725 ThrowException("May only switch on a constant pool value!");
1727 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1730 Inst : OptAssign InstVal {
1731 // Is this definition named?? if so, assign the name...
1732 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1737 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1738 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1739 $$->push_back(std::make_pair(getVal(*$1, $3),
1740 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1743 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1745 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1746 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1750 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1751 $$ = new std::vector<Value*>();
1754 | ValueRefList ',' ResolvedVal {
1759 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1760 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1762 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1763 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1764 ThrowException("Arithmetic operator requires integer or FP operands!");
1765 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1767 ThrowException("binary operator returned null!");
1770 | LogicalOps Types ValueRef ',' ValueRef {
1771 if (!(*$2)->isIntegral())
1772 ThrowException("Logical operator requires integral operands!");
1773 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1775 ThrowException("binary operator returned null!");
1778 | SetCondOps Types ValueRef ',' ValueRef {
1779 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1781 ThrowException("binary operator returned null!");
1785 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1786 << " Replacing with 'xor'.\n";
1788 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1790 ThrowException("Expected integral type for not instruction!");
1792 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1794 ThrowException("Could not create a xor instruction!");
1796 | ShiftOps ResolvedVal ',' ResolvedVal {
1797 if ($4->getType() != Type::UByteTy)
1798 ThrowException("Shift amount must be ubyte!");
1799 if (!$2->getType()->isInteger())
1800 ThrowException("Shift constant expression requires integer operand!");
1801 $$ = new ShiftInst($1, $2, $4);
1803 | CAST ResolvedVal TO Types {
1804 if (!$4->get()->isFirstClassType())
1805 ThrowException("cast instruction to a non-primitive type: '" +
1806 $4->get()->getDescription() + "'!");
1807 $$ = new CastInst($2, *$4);
1810 | VA_ARG ResolvedVal ',' Types {
1811 // FIXME: This is emulation code for an obsolete syntax. This should be
1812 // removed at some point.
1813 if (!ObsoleteVarArgs) {
1814 std::cerr << "WARNING: this file uses obsolete features. "
1815 << "Assemble and disassemble to update it.\n";
1816 ObsoleteVarArgs = true;
1819 // First, load the valist...
1820 Instruction *CurVAList = new LoadInst($2, "");
1821 CurBB->getInstList().push_back(CurVAList);
1823 // Emit the vaarg instruction.
1824 $$ = new VAArgInst(CurVAList, *$4);
1826 // Now we must advance the pointer and update it in memory.
1827 Instruction *TheVANext = new VANextInst(CurVAList, *$4);
1828 CurBB->getInstList().push_back(TheVANext);
1830 CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
1833 | VAARG ResolvedVal ',' Types {
1834 $$ = new VAArgInst($2, *$4);
1837 | VANEXT ResolvedVal ',' Types {
1838 $$ = new VANextInst($2, *$4);
1842 const Type *Ty = $2->front().first->getType();
1843 if (!Ty->isFirstClassType())
1844 ThrowException("PHI node operands must be of first class type!");
1845 $$ = new PHINode(Ty);
1846 $$->op_reserve($2->size()*2);
1847 while ($2->begin() != $2->end()) {
1848 if ($2->front().first->getType() != Ty)
1849 ThrowException("All elements of a PHI node must be of the same type!");
1850 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1853 delete $2; // Free the list...
1855 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1856 const PointerType *PFTy;
1857 const FunctionType *Ty;
1859 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1860 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1861 // Pull out the types of all of the arguments...
1862 std::vector<const Type*> ParamTypes;
1864 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1866 ParamTypes.push_back((*I)->getType());
1869 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1870 if (isVarArg) ParamTypes.pop_back();
1872 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1873 PFTy = PointerType::get(Ty);
1876 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1878 // Create the call node...
1879 if (!$5) { // Has no arguments?
1880 // Make sure no arguments is a good thing!
1881 if (Ty->getNumParams() != 0)
1882 ThrowException("No arguments passed to a function that "
1883 "expects arguments!");
1885 $$ = new CallInst(V, std::vector<Value*>());
1886 } else { // Has arguments?
1887 // Loop through FunctionType's arguments and ensure they are specified
1890 FunctionType::param_iterator I = Ty->param_begin();
1891 FunctionType::param_iterator E = Ty->param_end();
1892 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1894 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1895 if ((*ArgI)->getType() != *I)
1896 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1897 (*I)->getDescription() + "'!");
1899 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1900 ThrowException("Invalid number of parameters detected!");
1902 $$ = new CallInst(V, *$5);
1912 // IndexList - List of indices for GEP based instructions...
1913 IndexList : ',' ValueRefList {
1916 $$ = new std::vector<Value*>();
1919 OptVolatile : VOLATILE {
1927 MemoryInst : MALLOC Types {
1928 $$ = new MallocInst(*$2);
1931 | MALLOC Types ',' UINT ValueRef {
1932 $$ = new MallocInst(*$2, getVal($4, $5));
1936 $$ = new AllocaInst(*$2);
1939 | ALLOCA Types ',' UINT ValueRef {
1940 $$ = new AllocaInst(*$2, getVal($4, $5));
1943 | FREE ResolvedVal {
1944 if (!isa<PointerType>($2->getType()))
1945 ThrowException("Trying to free nonpointer type " +
1946 $2->getType()->getDescription() + "!");
1947 $$ = new FreeInst($2);
1950 | OptVolatile LOAD Types ValueRef {
1951 if (!isa<PointerType>($3->get()))
1952 ThrowException("Can't load from nonpointer type: " +
1953 (*$3)->getDescription());
1954 $$ = new LoadInst(getVal(*$3, $4), "", $1);
1957 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
1958 const PointerType *PT = dyn_cast<PointerType>($5->get());
1960 ThrowException("Can't store to a nonpointer type: " +
1961 (*$5)->getDescription());
1962 const Type *ElTy = PT->getElementType();
1963 if (ElTy != $3->getType())
1964 ThrowException("Can't store '" + $3->getType()->getDescription() +
1965 "' into space of type '" + ElTy->getDescription() + "'!");
1967 $$ = new StoreInst($3, getVal(*$5, $6), $1);
1970 | GETELEMENTPTR Types ValueRef IndexList {
1971 if (!isa<PointerType>($2->get()))
1972 ThrowException("getelementptr insn requires pointer operand!");
1973 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1974 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1975 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1976 delete $2; delete $4;
1981 int yyerror(const char *ErrorMsg) {
1983 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
1984 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
1985 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
1986 if (yychar == YYEMPTY)
1987 errMsg += "end-of-file.";
1989 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
1990 ThrowException(errMsg);