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"
23 #include "Support/DepthFirstIterator.h"
28 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
29 int yylex(); // declaration" of xxx warnings.
32 static Module *ParserResult;
33 std::string CurFilename;
35 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
36 // relating to upreferences in the input stream.
38 //#define DEBUG_UPREFS 1
40 #define UR_OUT(X) std::cerr << X
45 #define YYERROR_VERBOSE 1
47 // HACK ALERT: This variable is used to implement the automatic conversion of
48 // variable argument instructions from their old to new forms. When this
49 // compatiblity "Feature" is removed, this should be too.
51 static BasicBlock *CurBB;
52 static bool ObsoleteVarArgs;
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
59 static void ResolveDefinitions(std::vector<ValueList> &LateResolvers,
60 std::vector<ValueList> *FutureLateResolvers = 0);
62 static struct PerModuleInfo {
63 Module *CurrentModule;
64 std::vector<ValueList> Values; // Module level numbered definitions
65 std::vector<ValueList> LateResolveValues;
66 std::vector<PATypeHolder> Types;
67 std::map<ValID, PATypeHolder> LateResolveTypes;
69 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
70 // references to global values. Global values may be referenced before they
71 // are defined, and if so, the temporary object that they represent is held
72 // here. This is used for forward references of ConstantPointerRefs.
74 typedef std::map<std::pair<const PointerType *,
75 ValID>, GlobalVariable*> GlobalRefsType;
76 GlobalRefsType GlobalRefs;
79 // If we could not resolve some functions at function compilation time
80 // (calls to functions before they are defined), resolve them now... Types
81 // are resolved when the constant pool has been completely parsed.
83 ResolveDefinitions(LateResolveValues);
85 // Check to make sure that all global value forward references have been
88 if (!GlobalRefs.empty()) {
89 std::string UndefinedReferences = "Unresolved global references exist:\n";
91 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
93 UndefinedReferences += " " + I->first.first->getDescription() + " " +
94 I->first.second.getName() + "\n";
96 ThrowException(UndefinedReferences);
99 Values.clear(); // Clear out function local definitions
105 // DeclareNewGlobalValue - Called every time a new GV has been defined. This
106 // is used to remove things from the forward declaration map, resolving them
107 // to the correct thing as needed.
109 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
110 // Check to see if there is a forward reference to this global variable...
111 // if there is, eliminate it and patch the reference to use the new def'n.
112 GlobalRefsType::iterator I =
113 GlobalRefs.find(std::make_pair(GV->getType(), D));
115 if (I != GlobalRefs.end()) {
116 GlobalVariable *OldGV = I->second; // Get the placeholder...
117 I->first.second.destroy(); // Free string memory if necessary
119 // Loop over all of the uses of the GlobalValue. The only thing they are
120 // allowed to be is ConstantPointerRef's.
121 assert(OldGV->hasOneUse() && "Only one reference should exist!");
122 User *U = OldGV->use_back(); // Must be a ConstantPointerRef...
123 ConstantPointerRef *CPR = cast<ConstantPointerRef>(U);
125 // Change the const pool reference to point to the real global variable
126 // now. This should drop a use from the OldGV.
127 CPR->mutateReferences(OldGV, GV);
128 assert(OldGV->use_empty() && "All uses should be gone now!");
130 // Remove OldGV from the module...
131 CurrentModule->getGlobalList().remove(OldGV);
132 delete OldGV; // Delete the old placeholder
134 // Remove the map entry for the global now that it has been created...
141 static struct PerFunctionInfo {
142 Function *CurrentFunction; // Pointer to current function being created
144 std::vector<ValueList> Values; // Keep track of numbered definitions
145 std::vector<ValueList> LateResolveValues;
146 std::vector<PATypeHolder> Types;
147 std::map<ValID, PATypeHolder> LateResolveTypes;
148 bool isDeclare; // Is this function a forward declararation?
150 inline PerFunctionInfo() {
155 inline void FunctionStart(Function *M) {
159 void FunctionDone() {
160 // If we could not resolve some blocks at parsing time (forward branches)
161 // resolve the branches now...
162 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
164 // Make sure to resolve any constant expr references that might exist within
165 // the function we just declared itself.
167 if (CurrentFunction->hasName()) {
168 FID = ValID::create((char*)CurrentFunction->getName().c_str());
170 unsigned Slot = CurrentFunction->getType()->getUniqueID();
171 assert(CurModule.Values.size() > Slot && "Function not inserted?");
172 // Figure out which slot number if is...
173 for (unsigned i = 0; ; ++i) {
174 assert(i < CurModule.Values[Slot].size() && "Function not found!");
175 if (CurModule.Values[Slot][i] == CurrentFunction) {
176 FID = ValID::create((int)i);
181 CurModule.DeclareNewGlobalValue(CurrentFunction, FID);
183 Values.clear(); // Clear out function local definitions
188 } CurFun; // Info for the current function...
190 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
193 //===----------------------------------------------------------------------===//
194 // Code to handle definitions of all the types
195 //===----------------------------------------------------------------------===//
197 static int InsertValue(Value *D,
198 std::vector<ValueList> &ValueTab = CurFun.Values) {
199 if (D->hasName()) return -1; // Is this a numbered definition?
201 // Yes, insert the value into the value table...
202 unsigned type = D->getType()->getUniqueID();
203 if (ValueTab.size() <= type)
204 ValueTab.resize(type+1, ValueList());
205 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
206 ValueTab[type].push_back(D);
207 return ValueTab[type].size()-1;
210 // TODO: FIXME when Type are not const
211 static void InsertType(const Type *Ty, std::vector<PATypeHolder> &Types) {
215 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
217 case ValID::NumberVal: { // Is it a numbered definition?
218 unsigned Num = (unsigned)D.Num;
220 // Module constants occupy the lowest numbered slots...
221 if (Num < CurModule.Types.size())
222 return CurModule.Types[Num];
224 Num -= CurModule.Types.size();
226 // Check that the number is within bounds...
227 if (Num <= CurFun.Types.size())
228 return CurFun.Types[Num];
231 case ValID::NameVal: { // Is it a named definition?
232 std::string Name(D.Name);
233 SymbolTable *SymTab = 0;
235 if (inFunctionScope()) {
236 SymTab = &CurFun.CurrentFunction->getSymbolTable();
237 N = SymTab->lookup(Type::TypeTy, Name);
241 // Symbol table doesn't automatically chain yet... because the function
242 // hasn't been added to the module...
244 SymTab = &CurModule.CurrentModule->getSymbolTable();
245 N = SymTab->lookup(Type::TypeTy, Name);
249 D.destroy(); // Free old strdup'd memory...
250 return cast<Type>(N);
253 ThrowException("Internal parser error: Invalid symbol type reference!");
256 // If we reached here, we referenced either a symbol that we don't know about
257 // or an id number that hasn't been read yet. We may be referencing something
258 // forward, so just create an entry to be resolved later and get to it...
260 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
262 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
263 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
265 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
266 if (I != LateResolver.end()) {
270 Type *Typ = OpaqueType::get();
271 LateResolver.insert(std::make_pair(D, Typ));
275 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
276 SymbolTable &SymTab =
277 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
278 CurModule.CurrentModule->getSymbolTable();
279 return SymTab.lookup(Ty, Name);
282 // getValNonImprovising - Look up the value specified by the provided type and
283 // the provided ValID. If the value exists and has already been defined, return
284 // it. Otherwise return null.
286 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
287 if (isa<FunctionType>(Ty))
288 ThrowException("Functions are not values and "
289 "must be referenced as pointers");
292 case ValID::NumberVal: { // Is it a numbered definition?
293 unsigned type = Ty->getUniqueID();
294 unsigned Num = (unsigned)D.Num;
296 // Module constants occupy the lowest numbered slots...
297 if (type < CurModule.Values.size()) {
298 if (Num < CurModule.Values[type].size())
299 return CurModule.Values[type][Num];
301 Num -= CurModule.Values[type].size();
304 // Make sure that our type is within bounds
305 if (CurFun.Values.size() <= type) return 0;
307 // Check that the number is within bounds...
308 if (CurFun.Values[type].size() <= Num) return 0;
310 return CurFun.Values[type][Num];
313 case ValID::NameVal: { // Is it a named definition?
314 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
315 if (N == 0) return 0;
317 D.destroy(); // Free old strdup'd memory...
321 // Check to make sure that "Ty" is an integral type, and that our
322 // value will fit into the specified type...
323 case ValID::ConstSIntVal: // Is it a constant pool reference??
324 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
325 ThrowException("Signed integral constant '" +
326 itostr(D.ConstPool64) + "' is invalid for type '" +
327 Ty->getDescription() + "'!");
328 return ConstantSInt::get(Ty, D.ConstPool64);
330 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
331 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
332 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
333 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
334 "' is invalid or out of range!");
335 } else { // This is really a signed reference. Transmogrify.
336 return ConstantSInt::get(Ty, D.ConstPool64);
339 return ConstantUInt::get(Ty, D.UConstPool64);
342 case ValID::ConstFPVal: // Is it a floating point const pool reference?
343 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
344 ThrowException("FP constant invalid for type!!");
345 return ConstantFP::get(Ty, D.ConstPoolFP);
347 case ValID::ConstNullVal: // Is it a null value?
348 if (!isa<PointerType>(Ty))
349 ThrowException("Cannot create a a non pointer null!");
350 return ConstantPointerNull::get(cast<PointerType>(Ty));
352 case ValID::ConstantVal: // Fully resolved constant?
353 if (D.ConstantValue->getType() != Ty)
354 ThrowException("Constant expression type different from required type!");
355 return D.ConstantValue;
358 assert(0 && "Unhandled case!");
362 assert(0 && "Unhandled case!");
367 // getVal - This function is identical to getValNonImprovising, except that if a
368 // value is not already defined, it "improvises" by creating a placeholder var
369 // that looks and acts just like the requested variable. When the value is
370 // defined later, all uses of the placeholder variable are replaced with the
373 static Value *getVal(const Type *Ty, const ValID &D) {
374 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
376 // See if the value has already been defined...
377 Value *V = getValNonImprovising(Ty, D);
380 // If we reached here, we referenced either a symbol that we don't know about
381 // or an id number that hasn't been read yet. We may be referencing something
382 // forward, so just create an entry to be resolved later and get to it...
385 switch (Ty->getPrimitiveID()) {
386 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
387 default: d = new ValuePlaceHolder(Ty, D); break;
390 assert(d != 0 && "How did we not make something?");
391 if (inFunctionScope())
392 InsertValue(d, CurFun.LateResolveValues);
394 InsertValue(d, CurModule.LateResolveValues);
399 //===----------------------------------------------------------------------===//
400 // Code to handle forward references in instructions
401 //===----------------------------------------------------------------------===//
403 // This code handles the late binding needed with statements that reference
404 // values not defined yet... for example, a forward branch, or the PHI node for
407 // This keeps a table (CurFun.LateResolveValues) of all such forward references
408 // and back patchs after we are done.
411 // ResolveDefinitions - If we could not resolve some defs at parsing
412 // time (forward branches, phi functions for loops, etc...) resolve the
415 static void ResolveDefinitions(std::vector<ValueList> &LateResolvers,
416 std::vector<ValueList> *FutureLateResolvers) {
417 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
418 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
419 while (!LateResolvers[ty].empty()) {
420 Value *V = LateResolvers[ty].back();
421 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
423 LateResolvers[ty].pop_back();
424 ValID &DID = getValIDFromPlaceHolder(V);
426 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
428 V->replaceAllUsesWith(TheRealValue);
430 } else if (FutureLateResolvers) {
431 // Functions have their unresolved items forwarded to the module late
433 InsertValue(V, *FutureLateResolvers);
435 if (DID.Type == ValID::NameVal)
436 ThrowException("Reference to an invalid definition: '" +DID.getName()+
437 "' of type '" + V->getType()->getDescription() + "'",
438 getLineNumFromPlaceHolder(V));
440 ThrowException("Reference to an invalid definition: #" +
441 itostr(DID.Num) + " of type '" +
442 V->getType()->getDescription() + "'",
443 getLineNumFromPlaceHolder(V));
448 LateResolvers.clear();
451 // ResolveTypeTo - A brand new type was just declared. This means that (if
452 // name is not null) things referencing Name can be resolved. Otherwise, things
453 // refering to the number can be resolved. Do this now.
455 static void ResolveTypeTo(char *Name, const Type *ToTy) {
456 std::vector<PATypeHolder> &Types = inFunctionScope() ?
457 CurFun.Types : CurModule.Types;
460 if (Name) D = ValID::create(Name);
461 else D = ValID::create((int)Types.size());
463 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
464 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
466 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
467 if (I != LateResolver.end()) {
468 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
469 LateResolver.erase(I);
473 // ResolveTypes - At this point, all types should be resolved. Any that aren't
476 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
477 if (!LateResolveTypes.empty()) {
478 const ValID &DID = LateResolveTypes.begin()->first;
480 if (DID.Type == ValID::NameVal)
481 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
483 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
488 // setValueName - Set the specified value to the name given. The name may be
489 // null potentially, in which case this is a noop. The string passed in is
490 // assumed to be a malloc'd string buffer, and is freed by this function.
492 // This function returns true if the value has already been defined, but is
493 // allowed to be redefined in the specified context. If the name is a new name
494 // for the typeplane, false is returned.
496 static bool setValueName(Value *V, char *NameStr) {
497 if (NameStr == 0) return false;
499 std::string Name(NameStr); // Copy string
500 free(NameStr); // Free old string
502 if (V->getType() == Type::VoidTy)
503 ThrowException("Can't assign name '" + Name +
504 "' to a null valued instruction!");
506 SymbolTable &ST = inFunctionScope() ?
507 CurFun.CurrentFunction->getSymbolTable() :
508 CurModule.CurrentModule->getSymbolTable();
510 Value *Existing = ST.lookup(V->getType(), Name);
511 if (Existing) { // Inserting a name that is already defined???
512 // There is only one case where this is allowed: when we are refining an
513 // opaque type. In this case, Existing will be an opaque type.
514 if (const Type *Ty = dyn_cast<Type>(Existing)) {
515 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
516 // We ARE replacing an opaque type!
517 ((OpaqueType*)OpTy)->refineAbstractTypeTo(cast<Type>(V));
522 // Otherwise, we are a simple redefinition of a value, check to see if it
523 // is defined the same as the old one...
524 if (const Type *Ty = dyn_cast<Type>(Existing)) {
525 if (Ty == cast<Type>(V)) return true; // Yes, it's equal.
526 // std::cerr << "Type: " << Ty->getDescription() << " != "
527 // << cast<Type>(V)->getDescription() << "!\n";
528 } else if (const Constant *C = dyn_cast<Constant>(Existing)) {
529 if (C == V) return true; // Constants are equal to themselves
530 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
531 // We are allowed to redefine a global variable in two circumstances:
532 // 1. If at least one of the globals is uninitialized or
533 // 2. If both initializers have the same value.
535 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
536 if (!EGV->hasInitializer() || !GV->hasInitializer() ||
537 EGV->getInitializer() == GV->getInitializer()) {
539 // Make sure the existing global version gets the initializer! Make
540 // sure that it also gets marked const if the new version is.
541 if (GV->hasInitializer() && !EGV->hasInitializer())
542 EGV->setInitializer(GV->getInitializer());
543 if (GV->isConstant())
544 EGV->setConstant(true);
545 EGV->setLinkage(GV->getLinkage());
547 delete GV; // Destroy the duplicate!
548 return true; // They are equivalent!
552 ThrowException("Redefinition of value named '" + Name + "' in the '" +
553 V->getType()->getDescription() + "' type plane!");
556 V->setName(Name, &ST);
561 //===----------------------------------------------------------------------===//
562 // Code for handling upreferences in type names...
565 // TypeContains - Returns true if Ty contains E in it.
567 static bool TypeContains(const Type *Ty, const Type *E) {
568 return find(df_begin(Ty), df_end(Ty), E) != df_end(Ty);
572 static std::vector<std::pair<unsigned, OpaqueType *> > UpRefs;
574 static PATypeHolder HandleUpRefs(const Type *ty) {
576 UR_OUT("Type '" << ty->getDescription() <<
577 "' newly formed. Resolving upreferences.\n" <<
578 UpRefs.size() << " upreferences active!\n");
579 for (unsigned i = 0; i < UpRefs.size(); ) {
580 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
581 << UpRefs[i].second->getDescription() << ") = "
582 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << endl);
583 if (TypeContains(Ty, UpRefs[i].second)) {
584 unsigned Level = --UpRefs[i].first; // Decrement level of upreference
585 UR_OUT(" Uplevel Ref Level = " << Level << endl);
586 if (Level == 0) { // Upreference should be resolved!
587 UR_OUT(" * Resolving upreference for "
588 << UpRefs[i].second->getDescription() << endl;
589 std::string OldName = UpRefs[i].second->getDescription());
590 UpRefs[i].second->refineAbstractTypeTo(Ty);
591 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
592 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
593 << (const void*)Ty << ", " << Ty->getDescription() << endl);
598 ++i; // Otherwise, no resolve, move on...
600 // FIXME: TODO: this should return the updated type
605 //===----------------------------------------------------------------------===//
606 // RunVMAsmParser - Define an interface to this parser
607 //===----------------------------------------------------------------------===//
609 Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
611 CurFilename = Filename;
612 llvmAsmlineno = 1; // Reset the current line number...
613 ObsoleteVarArgs = false;
615 // Allocate a new module to read
616 CurModule.CurrentModule = new Module(Filename);
617 yyparse(); // Parse the file.
619 Module *Result = ParserResult;
621 // Check to see if they called va_start but not va_arg..
622 if (!ObsoleteVarArgs)
623 if (Function *F = Result->getNamedFunction("llvm.va_start"))
624 if (F->asize() == 1) {
625 std::cerr << "WARNING: this file uses obsolete features. "
626 << "Assemble and disassemble to update it.\n";
627 ObsoleteVarArgs = true;
631 if (ObsoleteVarArgs) {
632 // If the user is making use of obsolete varargs intrinsics, adjust them for
634 if (Function *F = Result->getNamedFunction("llvm.va_start")) {
635 assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
637 const Type *RetTy = F->getFunctionType()->getParamType(0);
638 RetTy = cast<PointerType>(RetTy)->getElementType();
639 Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
641 while (!F->use_empty()) {
642 CallInst *CI = cast<CallInst>(F->use_back());
643 Value *V = new CallInst(NF, "", CI);
644 new StoreInst(V, CI->getOperand(1), CI);
645 CI->getParent()->getInstList().erase(CI);
647 Result->getFunctionList().erase(F);
650 if (Function *F = Result->getNamedFunction("llvm.va_end")) {
651 assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
652 const Type *ArgTy = F->getFunctionType()->getParamType(0);
653 ArgTy = cast<PointerType>(ArgTy)->getElementType();
654 Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
657 while (!F->use_empty()) {
658 CallInst *CI = cast<CallInst>(F->use_back());
659 Value *V = new LoadInst(CI->getOperand(1), "", CI);
660 new CallInst(NF, V, "", CI);
661 CI->getParent()->getInstList().erase(CI);
663 Result->getFunctionList().erase(F);
666 if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
667 assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
668 const Type *ArgTy = F->getFunctionType()->getParamType(0);
669 ArgTy = cast<PointerType>(ArgTy)->getElementType();
670 Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
673 while (!F->use_empty()) {
674 CallInst *CI = cast<CallInst>(F->use_back());
675 Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
676 new StoreInst(V, CI->getOperand(1), CI);
677 CI->getParent()->getInstList().erase(CI);
679 Result->getFunctionList().erase(F);
683 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
693 Function *FunctionVal;
694 std::pair<PATypeHolder*, char*> *ArgVal;
695 BasicBlock *BasicBlockVal;
696 TerminatorInst *TermInstVal;
697 Instruction *InstVal;
700 const Type *PrimType;
701 PATypeHolder *TypeVal;
704 std::vector<std::pair<PATypeHolder*,char*> > *ArgList;
705 std::vector<Value*> *ValueList;
706 std::list<PATypeHolder> *TypeList;
707 std::list<std::pair<Value*,
708 BasicBlock*> > *PHIList; // Represent the RHS of PHI node
709 std::vector<std::pair<Constant*, BasicBlock*> > *JumpTable;
710 std::vector<Constant*> *ConstVector;
712 GlobalValue::LinkageTypes Linkage;
720 char *StrVal; // This memory is strdup'd!
721 ValID ValIDVal; // strdup'd memory maybe!
723 Instruction::BinaryOps BinaryOpVal;
724 Instruction::TermOps TermOpVal;
725 Instruction::MemoryOps MemOpVal;
726 Instruction::OtherOps OtherOpVal;
727 Module::Endianness Endianness;
730 %type <ModuleVal> Module FunctionList
731 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
732 %type <BasicBlockVal> BasicBlock InstructionList
733 %type <TermInstVal> BBTerminatorInst
734 %type <InstVal> Inst InstVal MemoryInst
735 %type <ConstVal> ConstVal ConstExpr
736 %type <ConstVector> ConstVector
737 %type <ArgList> ArgList ArgListH
738 %type <ArgVal> ArgVal
739 %type <PHIList> PHIList
740 %type <ValueList> ValueRefList ValueRefListE // For call param lists
741 %type <ValueList> IndexList // For GEP derived indices
742 %type <TypeList> TypeListI ArgTypeListI
743 %type <JumpTable> JumpTable
744 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
745 %type <BoolVal> OptVolatile // 'volatile' or not
746 %type <Linkage> OptLinkage
747 %type <Endianness> BigOrLittle
749 // ValueRef - Unresolved reference to a definition or BB
750 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
751 %type <ValueVal> ResolvedVal // <type> <valref> pair
752 // Tokens and types for handling constant integer values
754 // ESINT64VAL - A negative number within long long range
755 %token <SInt64Val> ESINT64VAL
757 // EUINT64VAL - A positive number within uns. long long range
758 %token <UInt64Val> EUINT64VAL
759 %type <SInt64Val> EINT64VAL
761 %token <SIntVal> SINTVAL // Signed 32 bit ints...
762 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
763 %type <SIntVal> INTVAL
764 %token <FPVal> FPVAL // Float or Double constant
767 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
768 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
769 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
770 %token <PrimType> FLOAT DOUBLE TYPE LABEL
772 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
773 %type <StrVal> Name OptName OptAssign
776 %token IMPLEMENTATION ZEROINITIALIZER TRUE FALSE BEGINTOK ENDTOK
777 %token DECLARE GLOBAL CONSTANT VOLATILE
778 %token TO EXCEPT DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE WEAK APPENDING
779 %token OPAQUE NOT EXTERNAL TARGET ENDIAN POINTERSIZE LITTLE BIG
781 // Basic Block Terminating Operators
782 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND
785 %type <BinaryOpVal> BinaryOps // all the binary operators
786 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
787 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
788 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
790 // Memory Instructions
791 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
794 %type <OtherOpVal> ShiftOps
795 %token <OtherOpVal> PHI_TOK CALL CAST SHL SHR VAARG VANEXT
796 %token VA_ARG // FIXME: OBSOLETE
801 // Handle constant integer size restriction and conversion...
805 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
806 ThrowException("Value too large for type!");
811 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
812 EINT64VAL : EUINT64VAL {
813 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
814 ThrowException("Value too large for type!");
818 // Operations that are notably excluded from this list include:
819 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
821 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
822 LogicalOps : AND | OR | XOR;
823 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
824 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
826 ShiftOps : SHL | SHR;
828 // These are some types that allow classification if we only want a particular
829 // thing... for example, only a signed, unsigned, or integral type.
830 SIntType : LONG | INT | SHORT | SBYTE;
831 UIntType : ULONG | UINT | USHORT | UBYTE;
832 IntType : SIntType | UIntType;
833 FPType : FLOAT | DOUBLE;
835 // OptAssign - Value producing statements have an optional assignment component
836 OptAssign : Name '=' {
843 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
844 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
845 WEAK { $$ = GlobalValue::WeakLinkage; } |
846 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
847 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
849 //===----------------------------------------------------------------------===//
850 // Types includes all predefined types... except void, because it can only be
851 // used in specific contexts (function returning void for example). To have
852 // access to it, a user must explicitly use TypesV.
855 // TypesV includes all of 'Types', but it also includes the void type.
856 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
857 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
861 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
866 // Derived types are added later...
868 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
869 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
871 $$ = new PATypeHolder(OpaqueType::get());
874 $$ = new PATypeHolder($1);
876 UpRTypes : SymbolicValueRef { // Named types are also simple types...
877 $$ = new PATypeHolder(getTypeVal($1));
880 // Include derived types in the Types production.
882 UpRTypes : '\\' EUINT64VAL { // Type UpReference
883 if ($2 > (uint64_t)INT64_MAX) ThrowException("Value out of range!");
884 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
885 UpRefs.push_back(std::make_pair((unsigned)$2, OT)); // Add to vector...
886 $$ = new PATypeHolder(OT);
887 UR_OUT("New Upreference!\n");
889 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
890 std::vector<const Type*> Params;
891 mapto($3->begin(), $3->end(), std::back_inserter(Params),
892 std::mem_fun_ref(&PATypeHolder::get));
893 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
894 if (isVarArg) Params.pop_back();
896 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
897 delete $3; // Delete the argument list
898 delete $1; // Delete the old type handle
900 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
901 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
904 | '{' TypeListI '}' { // Structure type?
905 std::vector<const Type*> Elements;
906 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
907 std::mem_fun_ref(&PATypeHolder::get));
909 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
912 | '{' '}' { // Empty structure type?
913 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
915 | UpRTypes '*' { // Pointer type?
916 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
920 // TypeList - Used for struct declarations and as a basis for function type
921 // declaration type lists
923 TypeListI : UpRTypes {
924 $$ = new std::list<PATypeHolder>();
925 $$->push_back(*$1); delete $1;
927 | TypeListI ',' UpRTypes {
928 ($$=$1)->push_back(*$3); delete $3;
931 // ArgTypeList - List of types for a function type declaration...
932 ArgTypeListI : TypeListI
933 | TypeListI ',' DOTDOTDOT {
934 ($$=$1)->push_back(Type::VoidTy);
937 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
940 $$ = new std::list<PATypeHolder>();
943 // ConstVal - The various declarations that go into the constant pool. This
944 // production is used ONLY to represent constants that show up AFTER a 'const',
945 // 'constant' or 'global' token at global scope. Constants that can be inlined
946 // into other expressions (such as integers and constexprs) are handled by the
947 // ResolvedVal, ValueRef and ConstValueRef productions.
949 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
950 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
952 ThrowException("Cannot make array constant with type: '" +
953 (*$1)->getDescription() + "'!");
954 const Type *ETy = ATy->getElementType();
955 int NumElements = ATy->getNumElements();
957 // Verify that we have the correct size...
958 if (NumElements != -1 && NumElements != (int)$3->size())
959 ThrowException("Type mismatch: constant sized array initialized with " +
960 utostr($3->size()) + " arguments, but has size of " +
961 itostr(NumElements) + "!");
963 // Verify all elements are correct type!
964 for (unsigned i = 0; i < $3->size(); i++) {
965 if (ETy != (*$3)[i]->getType())
966 ThrowException("Element #" + utostr(i) + " is not of type '" +
967 ETy->getDescription() +"' as required!\nIt is of type '"+
968 (*$3)[i]->getType()->getDescription() + "'.");
971 $$ = ConstantArray::get(ATy, *$3);
972 delete $1; delete $3;
975 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
977 ThrowException("Cannot make array constant with type: '" +
978 (*$1)->getDescription() + "'!");
980 int NumElements = ATy->getNumElements();
981 if (NumElements != -1 && NumElements != 0)
982 ThrowException("Type mismatch: constant sized array initialized with 0"
983 " arguments, but has size of " + itostr(NumElements) +"!");
984 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
987 | Types 'c' STRINGCONSTANT {
988 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
990 ThrowException("Cannot make array constant with type: '" +
991 (*$1)->getDescription() + "'!");
993 int NumElements = ATy->getNumElements();
994 const Type *ETy = ATy->getElementType();
995 char *EndStr = UnEscapeLexed($3, true);
996 if (NumElements != -1 && NumElements != (EndStr-$3))
997 ThrowException("Can't build string constant of size " +
998 itostr((int)(EndStr-$3)) +
999 " when array has size " + itostr(NumElements) + "!");
1000 std::vector<Constant*> Vals;
1001 if (ETy == Type::SByteTy) {
1002 for (char *C = $3; C != EndStr; ++C)
1003 Vals.push_back(ConstantSInt::get(ETy, *C));
1004 } else if (ETy == Type::UByteTy) {
1005 for (char *C = $3; C != EndStr; ++C)
1006 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1009 ThrowException("Cannot build string arrays of non byte sized elements!");
1012 $$ = ConstantArray::get(ATy, Vals);
1015 | Types '{' ConstVector '}' {
1016 const StructType *STy = dyn_cast<StructType>($1->get());
1018 ThrowException("Cannot make struct constant with type: '" +
1019 (*$1)->getDescription() + "'!");
1021 if ($3->size() != STy->getNumContainedTypes())
1022 ThrowException("Illegal number of initializers for structure type!");
1024 // Check to ensure that constants are compatible with the type initializer!
1025 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1026 if ((*$3)[i]->getType() != STy->getElementTypes()[i])
1027 ThrowException("Expected type '" +
1028 STy->getElementTypes()[i]->getDescription() +
1029 "' for element #" + utostr(i) +
1030 " of structure initializer!");
1032 $$ = ConstantStruct::get(STy, *$3);
1033 delete $1; delete $3;
1036 const StructType *STy = dyn_cast<StructType>($1->get());
1038 ThrowException("Cannot make struct constant with type: '" +
1039 (*$1)->getDescription() + "'!");
1041 if (STy->getNumContainedTypes() != 0)
1042 ThrowException("Illegal number of initializers for structure type!");
1044 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1048 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1050 ThrowException("Cannot make null pointer constant with type: '" +
1051 (*$1)->getDescription() + "'!");
1053 $$ = ConstantPointerNull::get(PTy);
1056 | Types SymbolicValueRef {
1057 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1059 ThrowException("Global const reference must be a pointer type!");
1061 // ConstExprs can exist in the body of a function, thus creating
1062 // ConstantPointerRefs whenever they refer to a variable. Because we are in
1063 // the context of a function, getValNonImprovising will search the functions
1064 // symbol table instead of the module symbol table for the global symbol,
1065 // which throws things all off. To get around this, we just tell
1066 // getValNonImprovising that we are at global scope here.
1068 Function *SavedCurFn = CurFun.CurrentFunction;
1069 CurFun.CurrentFunction = 0;
1071 Value *V = getValNonImprovising(Ty, $2);
1073 CurFun.CurrentFunction = SavedCurFn;
1075 // If this is an initializer for a constant pointer, which is referencing a
1076 // (currently) undefined variable, create a stub now that shall be replaced
1077 // in the future with the right type of variable.
1080 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1081 const PointerType *PT = cast<PointerType>(Ty);
1083 // First check to see if the forward references value is already created!
1084 PerModuleInfo::GlobalRefsType::iterator I =
1085 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1087 if (I != CurModule.GlobalRefs.end()) {
1088 V = I->second; // Placeholder already exists, use it...
1090 // TODO: Include line number info by creating a subclass of
1091 // TODO: GlobalVariable here that includes the said information!
1093 // Create a placeholder for the global variable reference...
1094 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
1096 GlobalValue::ExternalLinkage);
1097 // Keep track of the fact that we have a forward ref to recycle it
1098 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1100 // Must temporarily push this value into the module table...
1101 CurModule.CurrentModule->getGlobalList().push_back(GV);
1106 GlobalValue *GV = cast<GlobalValue>(V);
1107 $$ = ConstantPointerRef::get(GV);
1108 delete $1; // Free the type handle
1111 if ($1->get() != $2->getType())
1112 ThrowException("Mismatched types for constant expression!");
1116 | Types ZEROINITIALIZER {
1117 $$ = Constant::getNullValue($1->get());
1121 ConstVal : SIntType EINT64VAL { // integral constants
1122 if (!ConstantSInt::isValueValidForType($1, $2))
1123 ThrowException("Constant value doesn't fit in type!");
1124 $$ = ConstantSInt::get($1, $2);
1126 | UIntType EUINT64VAL { // integral constants
1127 if (!ConstantUInt::isValueValidForType($1, $2))
1128 ThrowException("Constant value doesn't fit in type!");
1129 $$ = ConstantUInt::get($1, $2);
1131 | BOOL TRUE { // Boolean constants
1132 $$ = ConstantBool::True;
1134 | BOOL FALSE { // Boolean constants
1135 $$ = ConstantBool::False;
1137 | FPType FPVAL { // Float & Double constants
1138 $$ = ConstantFP::get($1, $2);
1142 ConstExpr: CAST '(' ConstVal TO Types ')' {
1143 if (!$5->get()->isFirstClassType())
1144 ThrowException("cast constant expression to a non-primitive type: '" +
1145 $5->get()->getDescription() + "'!");
1146 $$ = ConstantExpr::getCast($3, $5->get());
1149 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1150 if (!isa<PointerType>($3->getType()))
1151 ThrowException("GetElementPtr requires a pointer operand!");
1154 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1156 ThrowException("Index list invalid for constant getelementptr!");
1158 std::vector<Constant*> IdxVec;
1159 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1160 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1161 IdxVec.push_back(C);
1163 ThrowException("Indices to constant getelementptr must be constants!");
1167 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1169 | BinaryOps '(' ConstVal ',' ConstVal ')' {
1170 if ($3->getType() != $5->getType())
1171 ThrowException("Binary operator types must match!");
1172 $$ = ConstantExpr::get($1, $3, $5);
1174 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1175 if ($5->getType() != Type::UByteTy)
1176 ThrowException("Shift count for shift constant must be unsigned byte!");
1177 if (!$3->getType()->isInteger())
1178 ThrowException("Shift constant expression requires integer operand!");
1179 $$ = ConstantExpr::getShift($1, $3, $5);
1183 // ConstVector - A list of comma separated constants.
1184 ConstVector : ConstVector ',' ConstVal {
1185 ($$ = $1)->push_back($3);
1188 $$ = new std::vector<Constant*>();
1193 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1194 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1197 //===----------------------------------------------------------------------===//
1198 // Rules to match Modules
1199 //===----------------------------------------------------------------------===//
1201 // Module rule: Capture the result of parsing the whole file into a result
1204 Module : FunctionList {
1205 $$ = ParserResult = $1;
1206 CurModule.ModuleDone();
1209 // FunctionList - A list of functions, preceeded by a constant pool.
1211 FunctionList : FunctionList Function {
1213 assert($2->getParent() == 0 && "Function already in module!");
1214 $1->getFunctionList().push_back($2);
1215 CurFun.FunctionDone();
1217 | FunctionList FunctionProto {
1220 | FunctionList IMPLEMENTATION {
1224 $$ = CurModule.CurrentModule;
1225 // Resolve circular types before we parse the body of the module
1226 ResolveTypes(CurModule.LateResolveTypes);
1229 // ConstPool - Constants with optional names assigned to them.
1230 ConstPool : ConstPool OptAssign CONST ConstVal {
1231 if (!setValueName($4, $2))
1234 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1235 // Eagerly resolve types. This is not an optimization, this is a
1236 // requirement that is due to the fact that we could have this:
1238 // %list = type { %list * }
1239 // %list = type { %list * } ; repeated type decl
1241 // If types are not resolved eagerly, then the two types will not be
1242 // determined to be the same type!
1244 ResolveTypeTo($2, $4->get());
1246 // TODO: FIXME when Type are not const
1247 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1248 // If this is not a redefinition of a type...
1250 InsertType($4->get(),
1251 inFunctionScope() ? CurFun.Types : CurModule.Types);
1257 | ConstPool FunctionProto { // Function prototypes can be in const pool
1259 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1260 const Type *Ty = $5->getType();
1261 // Global declarations appear in Constant Pool
1262 Constant *Initializer = $5;
1263 if (Initializer == 0)
1264 ThrowException("Global value initializer is not a constant!");
1266 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1267 if (!setValueName(GV, $2)) { // If not redefining...
1268 CurModule.CurrentModule->getGlobalList().push_back(GV);
1269 int Slot = InsertValue(GV, CurModule.Values);
1272 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1274 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1275 (char*)GV->getName().c_str()));
1279 | ConstPool OptAssign EXTERNAL GlobalType Types {
1280 const Type *Ty = *$5;
1281 // Global declarations appear in Constant Pool
1282 GlobalVariable *GV = new GlobalVariable(Ty,$4,GlobalValue::ExternalLinkage);
1283 if (!setValueName(GV, $2)) { // If not redefining...
1284 CurModule.CurrentModule->getGlobalList().push_back(GV);
1285 int Slot = InsertValue(GV, CurModule.Values);
1288 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1290 assert(GV->hasName() && "Not named and not numbered!?");
1291 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1292 (char*)GV->getName().c_str()));
1297 | ConstPool TARGET TargetDefinition {
1299 | /* empty: end of list */ {
1304 BigOrLittle : BIG { $$ = Module::BigEndian; };
1305 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1307 TargetDefinition : ENDIAN '=' BigOrLittle {
1308 CurModule.CurrentModule->setEndianness($3);
1310 | POINTERSIZE '=' EUINT64VAL {
1312 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1314 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1316 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1320 //===----------------------------------------------------------------------===//
1321 // Rules to match Function Headers
1322 //===----------------------------------------------------------------------===//
1324 Name : VAR_ID | STRINGCONSTANT;
1325 OptName : Name | /*empty*/ { $$ = 0; };
1327 ArgVal : Types OptName {
1328 if (*$1 == Type::VoidTy)
1329 ThrowException("void typed arguments are invalid!");
1330 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1333 ArgListH : ArgListH ',' ArgVal {
1339 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1344 ArgList : ArgListH {
1347 | ArgListH ',' DOTDOTDOT {
1349 $$->push_back(std::pair<PATypeHolder*,
1350 char*>(new PATypeHolder(Type::VoidTy), 0));
1353 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1354 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1360 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1362 std::string FunctionName($2);
1364 std::vector<const Type*> ParamTypeList;
1365 if ($4) { // If there are arguments...
1366 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1367 I != $4->end(); ++I)
1368 ParamTypeList.push_back(I->first->get());
1371 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1372 if (isVarArg) ParamTypeList.pop_back();
1374 const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1375 const PointerType *PFT = PointerType::get(FT);
1379 // Is the function already in symtab?
1380 if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1381 // Yes it is. If this is the case, either we need to be a forward decl,
1382 // or it needs to be.
1383 if (!CurFun.isDeclare && !Fn->isExternal())
1384 ThrowException("Redefinition of function '" + FunctionName + "'!");
1386 // If we found a preexisting function prototype, remove it from the
1387 // module, so that we don't get spurious conflicts with global & local
1390 CurModule.CurrentModule->getFunctionList().remove(Fn);
1392 // Make sure to strip off any argument names so we can't get conflicts...
1393 for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1396 } else { // Not already defined?
1397 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName);
1398 InsertValue(Fn, CurModule.Values);
1399 CurModule.DeclareNewGlobalValue(Fn, ValID::create($2));
1401 free($2); // Free strdup'd memory!
1403 CurFun.FunctionStart(Fn);
1405 // Add all of the arguments we parsed to the function...
1406 if ($4) { // Is null if empty...
1407 if (isVarArg) { // Nuke the last entry
1408 assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1409 "Not a varargs marker!");
1410 delete $4->back().first;
1411 $4->pop_back(); // Delete the last entry
1413 Function::aiterator ArgIt = Fn->abegin();
1414 for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1415 I != $4->end(); ++I, ++ArgIt) {
1416 delete I->first; // Delete the typeholder...
1418 if (setValueName(ArgIt, I->second)) // Insert arg into symtab...
1419 assert(0 && "No arg redef allowed!");
1424 delete $4; // We're now done with the argument list
1428 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1430 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1431 $$ = CurFun.CurrentFunction;
1433 // Make sure that we keep track of the linkage type even if there was a
1434 // previous "declare".
1437 // Resolve circular types before we parse the body of the function.
1438 ResolveTypes(CurFun.LateResolveTypes);
1441 END : ENDTOK | '}'; // Allow end of '}' to end a function
1443 Function : BasicBlockList END {
1447 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1448 $$ = CurFun.CurrentFunction;
1449 assert($$->getParent() == 0 && "Function already in module!");
1450 CurModule.CurrentModule->getFunctionList().push_back($$);
1451 CurFun.FunctionDone();
1454 //===----------------------------------------------------------------------===//
1455 // Rules to match Basic Blocks
1456 //===----------------------------------------------------------------------===//
1458 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1459 $$ = ValID::create($1);
1462 $$ = ValID::create($1);
1464 | FPVAL { // Perhaps it's an FP constant?
1465 $$ = ValID::create($1);
1468 $$ = ValID::create(ConstantBool::True);
1471 $$ = ValID::create(ConstantBool::False);
1474 $$ = ValID::createNull();
1477 $$ = ValID::create($1);
1480 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1483 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1484 $$ = ValID::create($1);
1486 | Name { // Is it a named reference...?
1487 $$ = ValID::create($1);
1490 // ValueRef - A reference to a definition... either constant or symbolic
1491 ValueRef : SymbolicValueRef | ConstValueRef;
1494 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1495 // type immediately preceeds the value reference, and allows complex constant
1496 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1497 ResolvedVal : Types ValueRef {
1498 $$ = getVal(*$1, $2); delete $1;
1501 BasicBlockList : BasicBlockList BasicBlock {
1502 ($$ = $1)->getBasicBlockList().push_back($2);
1504 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1505 ($$ = $1)->getBasicBlockList().push_back($2);
1509 // Basic blocks are terminated by branching instructions:
1510 // br, br/cc, switch, ret
1512 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1513 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1516 $1->getInstList().push_back($3);
1520 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1521 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1524 $2->getInstList().push_back($4);
1525 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1531 InstructionList : InstructionList Inst {
1532 $1->getInstList().push_back($2);
1536 $$ = CurBB = new BasicBlock();
1539 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1540 $$ = new ReturnInst($2);
1542 | RET VOID { // Return with no result...
1543 $$ = new ReturnInst();
1545 | BR LABEL ValueRef { // Unconditional Branch...
1546 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1547 } // Conditional Branch...
1548 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1549 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1550 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1551 getVal(Type::BoolTy, $3));
1553 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1554 SwitchInst *S = new SwitchInst(getVal($2, $3),
1555 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1558 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1561 S->addCase(I->first, I->second);
1563 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1564 SwitchInst *S = new SwitchInst(getVal($2, $3),
1565 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1568 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1569 EXCEPT ResolvedVal {
1570 const PointerType *PFTy;
1571 const FunctionType *Ty;
1573 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1574 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1575 // Pull out the types of all of the arguments...
1576 std::vector<const Type*> ParamTypes;
1578 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1580 ParamTypes.push_back((*I)->getType());
1583 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1584 if (isVarArg) ParamTypes.pop_back();
1586 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1587 PFTy = PointerType::get(Ty);
1591 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1593 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1594 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1596 if (Normal == 0 || Except == 0)
1597 ThrowException("Invoke instruction without label destinations!");
1599 // Create the call node...
1600 if (!$5) { // Has no arguments?
1601 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1602 } else { // Has arguments?
1603 // Loop through FunctionType's arguments and ensure they are specified
1606 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1607 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1608 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1610 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1611 if ((*ArgI)->getType() != *I)
1612 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1613 (*I)->getDescription() + "'!");
1615 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1616 ThrowException("Invalid number of parameters detected!");
1618 $$ = new InvokeInst(V, Normal, Except, *$5);
1623 $$ = new UnwindInst();
1628 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1630 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1632 ThrowException("May only switch on a constant pool value!");
1634 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1636 | IntType ConstValueRef ',' LABEL ValueRef {
1637 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1638 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1641 ThrowException("May only switch on a constant pool value!");
1643 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1646 Inst : OptAssign InstVal {
1647 // Is this definition named?? if so, assign the name...
1648 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1653 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1654 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1655 $$->push_back(std::make_pair(getVal(*$1, $3),
1656 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1659 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1661 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1662 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1666 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1667 $$ = new std::vector<Value*>();
1670 | ValueRefList ',' ResolvedVal {
1675 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1676 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1678 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1679 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1680 ThrowException("Arithmetic operator requires integer or FP operands!");
1681 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1683 ThrowException("binary operator returned null!");
1686 | LogicalOps Types ValueRef ',' ValueRef {
1687 if (!(*$2)->isIntegral())
1688 ThrowException("Logical operator requires integral operands!");
1689 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1691 ThrowException("binary operator returned null!");
1694 | SetCondOps Types ValueRef ',' ValueRef {
1695 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1697 ThrowException("binary operator returned null!");
1701 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1702 << " Replacing with 'xor'.\n";
1704 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1706 ThrowException("Expected integral type for not instruction!");
1708 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1710 ThrowException("Could not create a xor instruction!");
1712 | ShiftOps ResolvedVal ',' ResolvedVal {
1713 if ($4->getType() != Type::UByteTy)
1714 ThrowException("Shift amount must be ubyte!");
1715 if (!$2->getType()->isInteger())
1716 ThrowException("Shift constant expression requires integer operand!");
1717 $$ = new ShiftInst($1, $2, $4);
1719 | CAST ResolvedVal TO Types {
1720 if (!$4->get()->isFirstClassType())
1721 ThrowException("cast instruction to a non-primitive type: '" +
1722 $4->get()->getDescription() + "'!");
1723 $$ = new CastInst($2, *$4);
1726 | VA_ARG ResolvedVal ',' Types {
1727 // FIXME: This is emulation code for an obsolete syntax. This should be
1728 // removed at some point.
1729 if (!ObsoleteVarArgs) {
1730 std::cerr << "WARNING: this file uses obsolete features. "
1731 << "Assemble and disassemble to update it.\n";
1732 ObsoleteVarArgs = true;
1735 // First, load the valist...
1736 Instruction *CurVAList = new LoadInst($2, "");
1737 CurBB->getInstList().push_back(CurVAList);
1739 // Emit the vaarg instruction.
1740 $$ = new VAArgInst(CurVAList, *$4);
1742 // Now we must advance the pointer and update it in memory.
1743 Instruction *TheVANext = new VANextInst(CurVAList, *$4);
1744 CurBB->getInstList().push_back(TheVANext);
1746 CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
1749 | VAARG ResolvedVal ',' Types {
1750 $$ = new VAArgInst($2, *$4);
1753 | VANEXT ResolvedVal ',' Types {
1754 $$ = new VANextInst($2, *$4);
1758 const Type *Ty = $2->front().first->getType();
1759 if (!Ty->isFirstClassType())
1760 ThrowException("PHI node operands must be of first class type!");
1761 $$ = new PHINode(Ty);
1762 $$->op_reserve($2->size()*2);
1763 while ($2->begin() != $2->end()) {
1764 if ($2->front().first->getType() != Ty)
1765 ThrowException("All elements of a PHI node must be of the same type!");
1766 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1769 delete $2; // Free the list...
1771 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1772 const PointerType *PFTy;
1773 const FunctionType *Ty;
1775 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1776 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1777 // Pull out the types of all of the arguments...
1778 std::vector<const Type*> ParamTypes;
1780 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1782 ParamTypes.push_back((*I)->getType());
1785 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1786 if (isVarArg) ParamTypes.pop_back();
1788 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1789 PFTy = PointerType::get(Ty);
1793 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1795 // Create the call node...
1796 if (!$5) { // Has no arguments?
1797 // Make sure no arguments is a good thing!
1798 if (Ty->getNumParams() != 0)
1799 ThrowException("No arguments passed to a function that "
1800 "expects arguments!");
1802 $$ = new CallInst(V, std::vector<Value*>());
1803 } else { // Has arguments?
1804 // Loop through FunctionType's arguments and ensure they are specified
1807 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1808 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1809 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1811 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1812 if ((*ArgI)->getType() != *I)
1813 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1814 (*I)->getDescription() + "'!");
1816 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1817 ThrowException("Invalid number of parameters detected!");
1819 $$ = new CallInst(V, *$5);
1828 // IndexList - List of indices for GEP based instructions...
1829 IndexList : ',' ValueRefList {
1832 $$ = new std::vector<Value*>();
1835 OptVolatile : VOLATILE {
1843 MemoryInst : MALLOC Types {
1844 $$ = new MallocInst(*$2);
1847 | MALLOC Types ',' UINT ValueRef {
1848 $$ = new MallocInst(*$2, getVal($4, $5));
1852 $$ = new AllocaInst(*$2);
1855 | ALLOCA Types ',' UINT ValueRef {
1856 $$ = new AllocaInst(*$2, getVal($4, $5));
1859 | FREE ResolvedVal {
1860 if (!isa<PointerType>($2->getType()))
1861 ThrowException("Trying to free nonpointer type " +
1862 $2->getType()->getDescription() + "!");
1863 $$ = new FreeInst($2);
1866 | OptVolatile LOAD Types ValueRef {
1867 if (!isa<PointerType>($3->get()))
1868 ThrowException("Can't load from nonpointer type: " +
1869 (*$3)->getDescription());
1870 $$ = new LoadInst(getVal(*$3, $4), "", $1);
1873 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
1874 const PointerType *PT = dyn_cast<PointerType>($5->get());
1876 ThrowException("Can't store to a nonpointer type: " +
1877 (*$5)->getDescription());
1878 const Type *ElTy = PT->getElementType();
1879 if (ElTy != $3->getType())
1880 ThrowException("Can't store '" + $3->getType()->getDescription() +
1881 "' into space of type '" + ElTy->getDescription() + "'!");
1883 $$ = new StoreInst($3, getVal(*$5, $6), $1);
1886 | GETELEMENTPTR Types ValueRef IndexList {
1887 if (!isa<PointerType>($2->get()))
1888 ThrowException("getelementptr insn requires pointer operand!");
1889 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1890 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1891 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1892 delete $2; delete $4;
1896 int yyerror(const char *ErrorMsg) {
1898 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
1899 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
1900 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
1901 if (yychar == YYEMPTY)
1902 errMsg += "end-of-file.";
1904 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
1905 ThrowException(errMsg);