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 "UpgradeInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
29 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
30 // relating to upreferences in the input stream.
32 //#define DEBUG_UPREFS 1
34 #define UR_OUT(X) std::cerr << X
39 #define YYERROR_VERBOSE 1
40 #define YYINCLUDED_STDLIB_H
46 int yyerror(const char*);
47 static void warning(const std::string& WarningMsg);
51 std::istream* LexInput;
52 static std::string CurFilename;
54 // This bool controls whether attributes are ever added to function declarations
55 // definitions and calls.
56 static bool AddAttributes = false;
58 static Module *ParserResult;
59 static bool ObsoleteVarArgs;
60 static bool NewVarArgs;
61 static BasicBlock *CurBB;
62 static GlobalVariable *CurGV;
64 // This contains info used when building the body of a function. It is
65 // destroyed when the function is completed.
67 typedef std::vector<Value *> ValueList; // Numbered defs
69 typedef std::pair<std::string,const Type*> RenameMapKey;
70 typedef std::map<RenameMapKey,std::string> RenameMapType;
73 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
74 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
76 static struct PerModuleInfo {
77 Module *CurrentModule;
78 std::map<const Type *, ValueList> Values; // Module level numbered definitions
79 std::map<const Type *,ValueList> LateResolveValues;
80 std::vector<PATypeHolder> Types;
81 std::map<ValID, PATypeHolder> LateResolveTypes;
82 static Module::Endianness Endian;
83 static Module::PointerSize PointerSize;
84 RenameMapType RenameMap;
86 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
87 /// how they were referenced and on which line of the input they came from so
88 /// that we can resolve them later and print error messages as appropriate.
89 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
91 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
92 // references to global values. Global values may be referenced before they
93 // are defined, and if so, the temporary object that they represent is held
94 // here. This is used for forward references of GlobalValues.
96 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
98 GlobalRefsType GlobalRefs;
101 // If we could not resolve some functions at function compilation time
102 // (calls to functions before they are defined), resolve them now... Types
103 // are resolved when the constant pool has been completely parsed.
105 ResolveDefinitions(LateResolveValues);
107 // Check to make sure that all global value forward references have been
110 if (!GlobalRefs.empty()) {
111 std::string UndefinedReferences = "Unresolved global references exist:\n";
113 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
115 UndefinedReferences += " " + I->first.first->getDescription() + " " +
116 I->first.second.getName() + "\n";
118 error(UndefinedReferences);
122 if (CurrentModule->getDataLayout().empty()) {
123 std::string dataLayout;
124 if (Endian != Module::AnyEndianness)
125 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
126 if (PointerSize != Module::AnyPointerSize) {
127 if (!dataLayout.empty())
129 dataLayout.append(PointerSize == Module::Pointer64 ?
130 "p:64:64" : "p:32:32");
132 CurrentModule->setDataLayout(dataLayout);
135 Values.clear(); // Clear out function local definitions
140 // GetForwardRefForGlobal - Check to see if there is a forward reference
141 // for this global. If so, remove it from the GlobalRefs map and return it.
142 // If not, just return null.
143 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
144 // Check to see if there is a forward reference to this global variable...
145 // if there is, eliminate it and patch the reference to use the new def'n.
146 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
147 GlobalValue *Ret = 0;
148 if (I != GlobalRefs.end()) {
154 void setEndianness(Module::Endianness E) { Endian = E; }
155 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
158 Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
159 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
161 static struct PerFunctionInfo {
162 Function *CurrentFunction; // Pointer to current function being created
164 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
165 std::map<const Type*, ValueList> LateResolveValues;
166 bool isDeclare; // Is this function a forward declararation?
167 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
169 /// BBForwardRefs - When we see forward references to basic blocks, keep
170 /// track of them here.
171 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
172 std::vector<BasicBlock*> NumberedBlocks;
173 RenameMapType RenameMap;
176 inline PerFunctionInfo() {
179 Linkage = GlobalValue::ExternalLinkage;
182 inline void FunctionStart(Function *M) {
187 void FunctionDone() {
188 NumberedBlocks.clear();
190 // Any forward referenced blocks left?
191 if (!BBForwardRefs.empty()) {
192 error("Undefined reference to label " +
193 BBForwardRefs.begin()->first->getName());
197 // Resolve all forward references now.
198 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
200 Values.clear(); // Clear out function local definitions
204 Linkage = GlobalValue::ExternalLinkage;
206 } CurFun; // Info for the current function...
208 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
211 //===----------------------------------------------------------------------===//
212 // Code to handle definitions of all the types
213 //===----------------------------------------------------------------------===//
215 static int InsertValue(Value *V,
216 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
217 if (V->hasName()) return -1; // Is this a numbered definition?
219 // Yes, insert the value into the value table...
220 ValueList &List = ValueTab[V->getType()];
222 return List.size()-1;
225 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
227 case ValID::NumberVal: // Is it a numbered definition?
228 // Module constants occupy the lowest numbered slots...
229 if ((unsigned)D.Num < CurModule.Types.size()) {
230 return CurModule.Types[(unsigned)D.Num];
233 case ValID::NameVal: // Is it a named definition?
234 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
235 D.destroy(); // Free old strdup'd memory...
240 error("Internal parser error: Invalid symbol type reference");
244 // If we reached here, we referenced either a symbol that we don't know about
245 // or an id number that hasn't been read yet. We may be referencing something
246 // forward, so just create an entry to be resolved later and get to it...
248 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
251 if (inFunctionScope()) {
252 if (D.Type == ValID::NameVal) {
253 error("Reference to an undefined type: '" + D.getName() + "'");
256 error("Reference to an undefined type: #" + itostr(D.Num));
261 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
262 if (I != CurModule.LateResolveTypes.end())
265 Type *Typ = OpaqueType::get();
266 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
270 /// This function determines if two function types differ only in their use of
271 /// the sret parameter attribute in the first argument. If they are identical
272 /// in all other respects, it returns true. Otherwise, it returns false.
273 bool FuncTysDifferOnlyBySRet(const FunctionType *F1,
274 const FunctionType *F2) {
275 if (F1->getReturnType() != F2->getReturnType() ||
276 F1->getNumParams() != F2->getNumParams() ||
277 F1->getParamAttrs(0) != F2->getParamAttrs(0))
279 unsigned SRetMask = ~unsigned(FunctionType::StructRetAttribute);
280 for (unsigned i = 0; i < F1->getNumParams(); ++i) {
281 if (F1->getParamType(i) != F2->getParamType(i) ||
282 unsigned(F1->getParamAttrs(i+1)) & SRetMask !=
283 unsigned(F2->getParamAttrs(i+1)) & SRetMask)
289 // The upgrade of csretcc to sret param attribute may have caused a function
290 // to not be found because the param attribute changed the type of the called
291 // function. This helper function, used in getExistingValue, detects that
292 // situation and returns V if it occurs and 0 otherwise.
293 static Value* handleSRetFuncTypeMerge(Value *V, const Type* Ty) {
294 // Handle degenerate cases
297 if (V->getType() == Ty)
301 const PointerType *PF1 = dyn_cast<PointerType>(Ty);
302 const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
304 const FunctionType *FT1 =
305 dyn_cast<FunctionType>(PF1->getElementType());
306 const FunctionType *FT2 =
307 dyn_cast<FunctionType>(PF2->getElementType());
308 if (FT1 && FT2 && FuncTysDifferOnlyBySRet(FT1, FT2))
309 if (FT2->paramHasAttr(1, FunctionType::StructRetAttribute))
311 else if (Constant *C = dyn_cast<Constant>(V))
312 Result = ConstantExpr::getBitCast(C, PF1);
314 Result = new BitCastInst(V, PF1, "upgrd.cast", CurBB);
319 // getExistingValue - Look up the value specified by the provided type and
320 // the provided ValID. If the value exists and has already been defined, return
321 // it. Otherwise return null.
323 static Value *getExistingValue(const Type *Ty, const ValID &D) {
324 if (isa<FunctionType>(Ty)) {
325 error("Functions are not values and must be referenced as pointers");
329 case ValID::NumberVal: { // Is it a numbered definition?
330 unsigned Num = (unsigned)D.Num;
332 // Module constants occupy the lowest numbered slots...
333 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
334 if (VI != CurModule.Values.end()) {
335 if (Num < VI->second.size())
336 return VI->second[Num];
337 Num -= VI->second.size();
340 // Make sure that our type is within bounds
341 VI = CurFun.Values.find(Ty);
342 if (VI == CurFun.Values.end()) return 0;
344 // Check that the number is within bounds...
345 if (VI->second.size() <= Num) return 0;
347 return VI->second[Num];
350 case ValID::NameVal: { // Is it a named definition?
351 // Get the name out of the ID
352 std::string Name(D.Name);
354 RenameMapKey Key = std::make_pair(Name, Ty);
355 if (inFunctionScope()) {
356 // See if the name was renamed
357 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
358 std::string LookupName;
359 if (I != CurFun.RenameMap.end())
360 LookupName = I->second;
363 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
364 V = SymTab.lookup(LookupName);
365 V = handleSRetFuncTypeMerge(V, Ty);
368 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
369 std::string LookupName;
370 if (I != CurModule.RenameMap.end())
371 LookupName = I->second;
374 V = CurModule.CurrentModule->getValueSymbolTable().lookup(LookupName);
375 V = handleSRetFuncTypeMerge(V, Ty);
380 D.destroy(); // Free old strdup'd memory...
384 // Check to make sure that "Ty" is an integral type, and that our
385 // value will fit into the specified type...
386 case ValID::ConstSIntVal: // Is it a constant pool reference??
387 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
388 error("Signed integral constant '" + itostr(D.ConstPool64) +
389 "' is invalid for type '" + Ty->getDescription() + "'");
391 return ConstantInt::get(Ty, D.ConstPool64);
393 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
394 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
395 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
396 error("Integral constant '" + utostr(D.UConstPool64) +
397 "' is invalid or out of range");
398 else // This is really a signed reference. Transmogrify.
399 return ConstantInt::get(Ty, D.ConstPool64);
401 return ConstantInt::get(Ty, D.UConstPool64);
403 case ValID::ConstFPVal: // Is it a floating point const pool reference?
404 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
405 error("FP constant invalid for type");
406 return ConstantFP::get(Ty, D.ConstPoolFP);
408 case ValID::ConstNullVal: // Is it a null value?
409 if (!isa<PointerType>(Ty))
410 error("Cannot create a a non pointer null");
411 return ConstantPointerNull::get(cast<PointerType>(Ty));
413 case ValID::ConstUndefVal: // Is it an undef value?
414 return UndefValue::get(Ty);
416 case ValID::ConstZeroVal: // Is it a zero value?
417 return Constant::getNullValue(Ty);
419 case ValID::ConstantVal: // Fully resolved constant?
420 if (D.ConstantValue->getType() != Ty)
421 error("Constant expression type different from required type");
422 return D.ConstantValue;
424 case ValID::InlineAsmVal: { // Inline asm expression
425 const PointerType *PTy = dyn_cast<PointerType>(Ty);
426 const FunctionType *FTy =
427 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
428 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
429 error("Invalid type for asm constraint string");
430 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
431 D.IAD->HasSideEffects);
432 D.destroy(); // Free InlineAsmDescriptor.
436 assert(0 && "Unhandled case");
440 assert(0 && "Unhandled case");
444 // getVal - This function is identical to getExistingValue, except that if a
445 // value is not already defined, it "improvises" by creating a placeholder var
446 // that looks and acts just like the requested variable. When the value is
447 // defined later, all uses of the placeholder variable are replaced with the
450 static Value *getVal(const Type *Ty, const ValID &ID) {
451 if (Ty == Type::LabelTy)
452 error("Cannot use a basic block here");
454 // See if the value has already been defined.
455 Value *V = getExistingValue(Ty, ID);
458 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
459 error("Invalid use of a composite type");
461 // If we reached here, we referenced either a symbol that we don't know about
462 // or an id number that hasn't been read yet. We may be referencing something
463 // forward, so just create an entry to be resolved later and get to it...
464 V = new Argument(Ty);
466 // Remember where this forward reference came from. FIXME, shouldn't we try
467 // to recycle these things??
468 CurModule.PlaceHolderInfo.insert(
469 std::make_pair(V, std::make_pair(ID, Upgradelineno)));
471 if (inFunctionScope())
472 InsertValue(V, CurFun.LateResolveValues);
474 InsertValue(V, CurModule.LateResolveValues);
478 /// getBBVal - This is used for two purposes:
479 /// * If isDefinition is true, a new basic block with the specified ID is being
481 /// * If isDefinition is true, this is a reference to a basic block, which may
482 /// or may not be a forward reference.
484 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
485 assert(inFunctionScope() && "Can't get basic block at global scope");
491 error("Illegal label reference " + ID.getName());
493 case ValID::NumberVal: // Is it a numbered definition?
494 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
495 CurFun.NumberedBlocks.resize(ID.Num+1);
496 BB = CurFun.NumberedBlocks[ID.Num];
498 case ValID::NameVal: // Is it a named definition?
500 if (Value *N = CurFun.CurrentFunction->
501 getValueSymbolTable().lookup(Name)) {
502 if (N->getType() != Type::LabelTy)
503 error("Name '" + Name + "' does not refer to a BasicBlock");
504 BB = cast<BasicBlock>(N);
509 // See if the block has already been defined.
511 // If this is the definition of the block, make sure the existing value was
512 // just a forward reference. If it was a forward reference, there will be
513 // an entry for it in the PlaceHolderInfo map.
514 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
515 // The existing value was a definition, not a forward reference.
516 error("Redefinition of label " + ID.getName());
518 ID.destroy(); // Free strdup'd memory.
522 // Otherwise this block has not been seen before.
523 BB = new BasicBlock("", CurFun.CurrentFunction);
524 if (ID.Type == ValID::NameVal) {
525 BB->setName(ID.Name);
527 CurFun.NumberedBlocks[ID.Num] = BB;
530 // If this is not a definition, keep track of it so we can use it as a forward
533 // Remember where this forward reference came from.
534 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
536 // The forward declaration could have been inserted anywhere in the
537 // function: insert it into the correct place now.
538 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
539 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
546 //===----------------------------------------------------------------------===//
547 // Code to handle forward references in instructions
548 //===----------------------------------------------------------------------===//
550 // This code handles the late binding needed with statements that reference
551 // values not defined yet... for example, a forward branch, or the PHI node for
554 // This keeps a table (CurFun.LateResolveValues) of all such forward references
555 // and back patchs after we are done.
558 // ResolveDefinitions - If we could not resolve some defs at parsing
559 // time (forward branches, phi functions for loops, etc...) resolve the
563 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
564 std::map<const Type*,ValueList> *FutureLateResolvers) {
566 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
567 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
568 E = LateResolvers.end(); LRI != E; ++LRI) {
569 const Type* Ty = LRI->first;
570 ValueList &List = LRI->second;
571 while (!List.empty()) {
572 Value *V = List.back();
575 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
576 CurModule.PlaceHolderInfo.find(V);
577 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
579 ValID &DID = PHI->second.first;
581 Value *TheRealValue = getExistingValue(Ty, DID);
583 V->replaceAllUsesWith(TheRealValue);
585 CurModule.PlaceHolderInfo.erase(PHI);
586 } else if (FutureLateResolvers) {
587 // Functions have their unresolved items forwarded to the module late
589 InsertValue(V, *FutureLateResolvers);
591 if (DID.Type == ValID::NameVal) {
592 error("Reference to an invalid definition: '" + DID.getName() +
593 "' of type '" + V->getType()->getDescription() + "'",
597 error("Reference to an invalid definition: #" +
598 itostr(DID.Num) + " of type '" +
599 V->getType()->getDescription() + "'", PHI->second.second);
606 LateResolvers.clear();
609 // ResolveTypeTo - A brand new type was just declared. This means that (if
610 // name is not null) things referencing Name can be resolved. Otherwise, things
611 // refering to the number can be resolved. Do this now.
613 static void ResolveTypeTo(char *Name, const Type *ToTy) {
615 if (Name) D = ValID::create(Name);
616 else D = ValID::create((int)CurModule.Types.size());
618 std::map<ValID, PATypeHolder>::iterator I =
619 CurModule.LateResolveTypes.find(D);
620 if (I != CurModule.LateResolveTypes.end()) {
621 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
622 CurModule.LateResolveTypes.erase(I);
626 /// @brief This just makes any name given to it unique, up to MAX_UINT times.
627 static std::string makeNameUnique(const std::string& Name) {
628 static unsigned UniqueNameCounter = 1;
629 std::string Result(Name);
630 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
634 /// This is the implementation portion of TypeHasInteger. It traverses the
635 /// type given, avoiding recursive types, and returns true as soon as it finds
636 /// an integer type. If no integer type is found, it returns false.
637 static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
638 // Handle some easy cases
639 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
643 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
644 return STy->getElementType()->isInteger();
646 // Avoid type structure recursion
647 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
652 // Push us on the type stack
655 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
656 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
658 FunctionType::param_iterator I = FTy->param_begin();
659 FunctionType::param_iterator E = FTy->param_end();
661 if (TypeHasIntegerI(*I, Stack))
664 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
665 StructType::element_iterator I = STy->element_begin();
666 StructType::element_iterator E = STy->element_end();
667 for (; I != E; ++I) {
668 if (TypeHasIntegerI(*I, Stack))
673 // There shouldn't be anything else, but its definitely not integer
674 assert(0 && "What type is this?");
678 /// This is the interface to TypeHasIntegerI. It just provides the type stack,
679 /// to avoid recursion, and then calls TypeHasIntegerI.
680 static inline bool TypeHasInteger(const Type *Ty) {
681 std::vector<const Type*> TyStack;
682 return TypeHasIntegerI(Ty, TyStack);
685 // setValueName - Set the specified value to the name given. The name may be
686 // null potentially, in which case this is a noop. The string passed in is
687 // assumed to be a malloc'd string buffer, and is free'd by this function.
689 static void setValueName(Value *V, char *NameStr) {
691 std::string Name(NameStr); // Copy string
692 free(NameStr); // Free old string
694 if (V->getType() == Type::VoidTy) {
695 error("Can't assign name '" + Name + "' to value with void type");
699 assert(inFunctionScope() && "Must be in function scope");
701 // Search the function's symbol table for an existing value of this name
702 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
703 Value* Existing = ST.lookup(Name);
705 // An existing value of the same name was found. This might have happened
706 // because of the integer type planes collapsing in LLVM 2.0.
707 if (Existing->getType() == V->getType() &&
708 !TypeHasInteger(Existing->getType())) {
709 // If the type does not contain any integers in them then this can't be
710 // a type plane collapsing issue. It truly is a redefinition and we
711 // should error out as the assembly is invalid.
712 error("Redefinition of value named '" + Name + "' of type '" +
713 V->getType()->getDescription() + "'");
716 // In LLVM 2.0 we don't allow names to be re-used for any values in a
717 // function, regardless of Type. Previously re-use of names was okay as
718 // long as they were distinct types. With type planes collapsing because
719 // of the signedness change and because of PR411, this can no longer be
720 // supported. We must search the entire symbol table for a conflicting
721 // name and make the name unique. No warning is needed as this can't
723 std::string NewName = makeNameUnique(Name);
724 // We're changing the name but it will probably be used by other
725 // instructions as operands later on. Consequently we have to retain
726 // a mapping of the renaming that we're doing.
727 RenameMapKey Key = std::make_pair(Name,V->getType());
728 CurFun.RenameMap[Key] = NewName;
737 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
738 /// this is a declaration, otherwise it is a definition.
739 static GlobalVariable *
740 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
741 bool isConstantGlobal, const Type *Ty,
742 Constant *Initializer) {
743 if (isa<FunctionType>(Ty))
744 error("Cannot declare global vars of function type");
746 const PointerType *PTy = PointerType::get(Ty);
750 Name = NameStr; // Copy string
751 free(NameStr); // Free old string
754 // See if this global value was forward referenced. If so, recycle the
758 ID = ValID::create((char*)Name.c_str());
760 ID = ValID::create((int)CurModule.Values[PTy].size());
763 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
764 // Move the global to the end of the list, from whereever it was
765 // previously inserted.
766 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
767 CurModule.CurrentModule->getGlobalList().remove(GV);
768 CurModule.CurrentModule->getGlobalList().push_back(GV);
769 GV->setInitializer(Initializer);
770 GV->setLinkage(Linkage);
771 GV->setConstant(isConstantGlobal);
772 InsertValue(GV, CurModule.Values);
776 // If this global has a name, check to see if there is already a definition
777 // of this global in the module and emit warnings if there are conflicts.
779 // The global has a name. See if there's an existing one of the same name.
780 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
781 // We found an existing global ov the same name. This isn't allowed
782 // in LLVM 2.0. Consequently, we must alter the name of the global so it
783 // can at least compile. This can happen because of type planes
784 // There is alread a global of the same name which means there is a
785 // conflict. Let's see what we can do about it.
786 std::string NewName(makeNameUnique(Name));
787 if (Linkage == GlobalValue::InternalLinkage) {
788 // The linkage type is internal so just warn about the rename without
789 // invoking "scarey language" about linkage failures. GVars with
790 // InternalLinkage can be renamed at will.
791 warning("Global variable '" + Name + "' was renamed to '"+
794 // The linkage of this gval is external so we can't reliably rename
795 // it because it could potentially create a linking problem.
796 // However, we can't leave the name conflict in the output either or
797 // it won't assemble with LLVM 2.0. So, all we can do is rename
798 // this one to something unique and emit a warning about the problem.
799 warning("Renaming global variable '" + Name + "' to '" + NewName +
800 "' may cause linkage errors");
803 // Put the renaming in the global rename map
804 RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
805 CurModule.RenameMap[Key] = NewName;
812 // Otherwise there is no existing GV to use, create one now.
814 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
815 CurModule.CurrentModule);
816 InsertValue(GV, CurModule.Values);
820 // setTypeName - Set the specified type to the name given. The name may be
821 // null potentially, in which case this is a noop. The string passed in is
822 // assumed to be a malloc'd string buffer, and is freed by this function.
824 // This function returns true if the type has already been defined, but is
825 // allowed to be redefined in the specified context. If the name is a new name
826 // for the type plane, it is inserted and false is returned.
827 static bool setTypeName(const Type *T, char *NameStr) {
828 assert(!inFunctionScope() && "Can't give types function-local names");
829 if (NameStr == 0) return false;
831 std::string Name(NameStr); // Copy string
832 free(NameStr); // Free old string
834 // We don't allow assigning names to void type
835 if (T == Type::VoidTy) {
836 error("Can't assign name '" + Name + "' to the void type");
840 // Set the type name, checking for conflicts as we do so.
841 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
843 if (AlreadyExists) { // Inserting a name that is already defined???
844 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
845 assert(Existing && "Conflict but no matching type?");
847 // There is only one case where this is allowed: when we are refining an
848 // opaque type. In this case, Existing will be an opaque type.
849 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
850 // We ARE replacing an opaque type!
851 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
855 // Otherwise, this is an attempt to redefine a type. That's okay if
856 // the redefinition is identical to the original. This will be so if
857 // Existing and T point to the same Type object. In this one case we
858 // allow the equivalent redefinition.
859 if (Existing == T) return true; // Yes, it's equal.
861 // Any other kind of (non-equivalent) redefinition is an error.
862 error("Redefinition of type named '" + Name + "' in the '" +
863 T->getDescription() + "' type plane");
869 //===----------------------------------------------------------------------===//
870 // Code for handling upreferences in type names...
873 // TypeContains - Returns true if Ty directly contains E in it.
875 static bool TypeContains(const Type *Ty, const Type *E) {
876 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
877 E) != Ty->subtype_end();
882 // NestingLevel - The number of nesting levels that need to be popped before
883 // this type is resolved.
884 unsigned NestingLevel;
886 // LastContainedTy - This is the type at the current binding level for the
887 // type. Every time we reduce the nesting level, this gets updated.
888 const Type *LastContainedTy;
890 // UpRefTy - This is the actual opaque type that the upreference is
894 UpRefRecord(unsigned NL, OpaqueType *URTy)
895 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
899 // UpRefs - A list of the outstanding upreferences that need to be resolved.
900 static std::vector<UpRefRecord> UpRefs;
902 /// HandleUpRefs - Every time we finish a new layer of types, this function is
903 /// called. It loops through the UpRefs vector, which is a list of the
904 /// currently active types. For each type, if the up reference is contained in
905 /// the newly completed type, we decrement the level count. When the level
906 /// count reaches zero, the upreferenced type is the type that is passed in:
907 /// thus we can complete the cycle.
909 static PATypeHolder HandleUpRefs(const Type *ty) {
910 // If Ty isn't abstract, or if there are no up-references in it, then there is
911 // nothing to resolve here.
912 if (!ty->isAbstract() || UpRefs.empty()) return ty;
915 UR_OUT("Type '" << Ty->getDescription() <<
916 "' newly formed. Resolving upreferences.\n" <<
917 UpRefs.size() << " upreferences active!\n");
919 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
920 // to zero), we resolve them all together before we resolve them to Ty. At
921 // the end of the loop, if there is anything to resolve to Ty, it will be in
923 OpaqueType *TypeToResolve = 0;
925 for (unsigned i = 0; i != UpRefs.size(); ++i) {
926 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
927 << UpRefs[i].second->getDescription() << ") = "
928 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
929 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
930 // Decrement level of upreference
931 unsigned Level = --UpRefs[i].NestingLevel;
932 UpRefs[i].LastContainedTy = Ty;
933 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
934 if (Level == 0) { // Upreference should be resolved!
935 if (!TypeToResolve) {
936 TypeToResolve = UpRefs[i].UpRefTy;
938 UR_OUT(" * Resolving upreference for "
939 << UpRefs[i].second->getDescription() << "\n";
940 std::string OldName = UpRefs[i].UpRefTy->getDescription());
941 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
942 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
943 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
945 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
946 --i; // Do not skip the next element...
952 UR_OUT(" * Resolving upreference for "
953 << UpRefs[i].second->getDescription() << "\n";
954 std::string OldName = TypeToResolve->getDescription());
955 TypeToResolve->refineAbstractTypeTo(Ty);
961 static inline Instruction::TermOps
962 getTermOp(TermOps op) {
964 default : assert(0 && "Invalid OldTermOp");
965 case RetOp : return Instruction::Ret;
966 case BrOp : return Instruction::Br;
967 case SwitchOp : return Instruction::Switch;
968 case InvokeOp : return Instruction::Invoke;
969 case UnwindOp : return Instruction::Unwind;
970 case UnreachableOp: return Instruction::Unreachable;
974 static inline Instruction::BinaryOps
975 getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
977 default : assert(0 && "Invalid OldBinaryOps");
983 case SetGT : assert(0 && "Should use getCompareOp");
984 case AddOp : return Instruction::Add;
985 case SubOp : return Instruction::Sub;
986 case MulOp : return Instruction::Mul;
988 // This is an obsolete instruction so we must upgrade it based on the
989 // types of its operands.
990 bool isFP = Ty->isFloatingPoint();
991 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
992 // If its a packed type we want to use the element type
993 isFP = PTy->getElementType()->isFloatingPoint();
995 return Instruction::FDiv;
996 else if (Sign == Signed)
997 return Instruction::SDiv;
998 return Instruction::UDiv;
1000 case UDivOp : return Instruction::UDiv;
1001 case SDivOp : return Instruction::SDiv;
1002 case FDivOp : return Instruction::FDiv;
1004 // This is an obsolete instruction so we must upgrade it based on the
1005 // types of its operands.
1006 bool isFP = Ty->isFloatingPoint();
1007 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
1008 // If its a packed type we want to use the element type
1009 isFP = PTy->getElementType()->isFloatingPoint();
1010 // Select correct opcode
1012 return Instruction::FRem;
1013 else if (Sign == Signed)
1014 return Instruction::SRem;
1015 return Instruction::URem;
1017 case URemOp : return Instruction::URem;
1018 case SRemOp : return Instruction::SRem;
1019 case FRemOp : return Instruction::FRem;
1020 case LShrOp : return Instruction::LShr;
1021 case AShrOp : return Instruction::AShr;
1022 case ShlOp : return Instruction::Shl;
1025 return Instruction::AShr;
1026 return Instruction::LShr;
1027 case AndOp : return Instruction::And;
1028 case OrOp : return Instruction::Or;
1029 case XorOp : return Instruction::Xor;
1033 static inline Instruction::OtherOps
1034 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1036 bool isSigned = Sign == Signed;
1037 bool isFP = Ty->isFloatingPoint();
1039 default : assert(0 && "Invalid OldSetCC");
1042 predicate = FCmpInst::FCMP_OEQ;
1043 return Instruction::FCmp;
1045 predicate = ICmpInst::ICMP_EQ;
1046 return Instruction::ICmp;
1050 predicate = FCmpInst::FCMP_UNE;
1051 return Instruction::FCmp;
1053 predicate = ICmpInst::ICMP_NE;
1054 return Instruction::ICmp;
1058 predicate = FCmpInst::FCMP_OLE;
1059 return Instruction::FCmp;
1062 predicate = ICmpInst::ICMP_SLE;
1064 predicate = ICmpInst::ICMP_ULE;
1065 return Instruction::ICmp;
1069 predicate = FCmpInst::FCMP_OGE;
1070 return Instruction::FCmp;
1073 predicate = ICmpInst::ICMP_SGE;
1075 predicate = ICmpInst::ICMP_UGE;
1076 return Instruction::ICmp;
1080 predicate = FCmpInst::FCMP_OLT;
1081 return Instruction::FCmp;
1084 predicate = ICmpInst::ICMP_SLT;
1086 predicate = ICmpInst::ICMP_ULT;
1087 return Instruction::ICmp;
1091 predicate = FCmpInst::FCMP_OGT;
1092 return Instruction::FCmp;
1095 predicate = ICmpInst::ICMP_SGT;
1097 predicate = ICmpInst::ICMP_UGT;
1098 return Instruction::ICmp;
1103 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1105 default : assert(0 && "Invalid OldMemoryOps");
1106 case MallocOp : return Instruction::Malloc;
1107 case FreeOp : return Instruction::Free;
1108 case AllocaOp : return Instruction::Alloca;
1109 case LoadOp : return Instruction::Load;
1110 case StoreOp : return Instruction::Store;
1111 case GetElementPtrOp : return Instruction::GetElementPtr;
1115 static inline Instruction::OtherOps
1116 getOtherOp(OtherOps op, Signedness Sign) {
1118 default : assert(0 && "Invalid OldOtherOps");
1119 case PHIOp : return Instruction::PHI;
1120 case CallOp : return Instruction::Call;
1121 case SelectOp : return Instruction::Select;
1122 case UserOp1 : return Instruction::UserOp1;
1123 case UserOp2 : return Instruction::UserOp2;
1124 case VAArg : return Instruction::VAArg;
1125 case ExtractElementOp : return Instruction::ExtractElement;
1126 case InsertElementOp : return Instruction::InsertElement;
1127 case ShuffleVectorOp : return Instruction::ShuffleVector;
1128 case ICmpOp : return Instruction::ICmp;
1129 case FCmpOp : return Instruction::FCmp;
1133 static inline Value*
1134 getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1135 Signedness DstSign, bool ForceInstruction = false) {
1136 Instruction::CastOps Opcode;
1137 const Type* SrcTy = Src->getType();
1139 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1140 // fp -> ptr cast is no longer supported but we must upgrade this
1141 // by doing a double cast: fp -> int -> ptr
1142 SrcTy = Type::Int64Ty;
1143 Opcode = Instruction::IntToPtr;
1144 if (isa<Constant>(Src)) {
1145 Src = ConstantExpr::getCast(Instruction::FPToUI,
1146 cast<Constant>(Src), SrcTy);
1148 std::string NewName(makeNameUnique(Src->getName()));
1149 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1151 } else if (isa<IntegerType>(DstTy) &&
1152 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1153 // cast type %x to bool was previously defined as setne type %x, null
1154 // The cast semantic is now to truncate, not compare so we must retain
1155 // the original intent by replacing the cast with a setne
1156 Constant* Null = Constant::getNullValue(SrcTy);
1157 Instruction::OtherOps Opcode = Instruction::ICmp;
1158 unsigned short predicate = ICmpInst::ICMP_NE;
1159 if (SrcTy->isFloatingPoint()) {
1160 Opcode = Instruction::FCmp;
1161 predicate = FCmpInst::FCMP_ONE;
1162 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1163 error("Invalid cast to bool");
1165 if (isa<Constant>(Src) && !ForceInstruction)
1166 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1168 return CmpInst::create(Opcode, predicate, Src, Null);
1170 // Determine the opcode to use by calling CastInst::getCastOpcode
1172 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1174 } else switch (op) {
1175 default: assert(0 && "Invalid cast token");
1176 case TruncOp: Opcode = Instruction::Trunc; break;
1177 case ZExtOp: Opcode = Instruction::ZExt; break;
1178 case SExtOp: Opcode = Instruction::SExt; break;
1179 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1180 case FPExtOp: Opcode = Instruction::FPExt; break;
1181 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1182 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1183 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1184 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1185 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1186 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1187 case BitCastOp: Opcode = Instruction::BitCast; break;
1190 if (isa<Constant>(Src) && !ForceInstruction)
1191 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1192 return CastInst::create(Opcode, Src, DstTy);
1195 static Instruction *
1196 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1197 std::vector<Value*>& Args) {
1199 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1200 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1201 if (Args.size() != 2)
1202 error("Invalid prototype for " + Name + " prototype");
1203 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1205 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1206 std::vector<const Type*> Params;
1207 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1208 if (Args.size() != 1)
1209 error("Invalid prototype for " + Name + " prototype");
1210 Params.push_back(PtrTy);
1211 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1212 const PointerType *PFTy = PointerType::get(FTy);
1213 Value* Func = getVal(PFTy, ID);
1214 Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
1215 return new CallInst(Func, Args);
1216 } else if (Name == "llvm.va_copy") {
1217 if (Args.size() != 2)
1218 error("Invalid prototype for " + Name + " prototype");
1219 Params.push_back(PtrTy);
1220 Params.push_back(PtrTy);
1221 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1222 const PointerType *PFTy = PointerType::get(FTy);
1223 Value* Func = getVal(PFTy, ID);
1224 std::string InstName0(makeNameUnique("va0"));
1225 std::string InstName1(makeNameUnique("va1"));
1226 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1227 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1228 return new CallInst(Func, Args);
1234 const Type* upgradeGEPIndices(const Type* PTy,
1235 std::vector<ValueInfo> *Indices,
1236 std::vector<Value*> &VIndices,
1237 std::vector<Constant*> *CIndices = 0) {
1238 // Traverse the indices with a gep_type_iterator so we can build the list
1239 // of constant and value indices for use later. Also perform upgrades
1241 if (CIndices) CIndices->clear();
1242 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1243 VIndices.push_back((*Indices)[i].V);
1244 generic_gep_type_iterator<std::vector<Value*>::iterator>
1245 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1246 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1247 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1248 Value *Index = VIndices[i];
1249 if (CIndices && !isa<Constant>(Index))
1250 error("Indices to constant getelementptr must be constants");
1251 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1252 // struct indices to i32 struct indices with ZExt for compatibility.
1253 else if (isa<StructType>(*GTI)) { // Only change struct indices
1254 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1255 if (CUI->getType()->getBitWidth() == 8)
1257 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1259 // Make sure that unsigned SequentialType indices are zext'd to
1260 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1261 // all indices for SequentialType elements. We must retain the same
1262 // semantic (zext) for unsigned types.
1263 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1264 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned) {
1266 Index = ConstantExpr::getCast(Instruction::ZExt,
1267 cast<Constant>(Index), Type::Int64Ty);
1269 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1270 makeNameUnique("gep"), CurBB);
1271 VIndices[i] = Index;
1274 // Add to the CIndices list, if requested.
1276 CIndices->push_back(cast<Constant>(Index));
1280 GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1282 error("Index list invalid for constant getelementptr");
1286 unsigned upgradeCallingConv(unsigned CC) {
1288 case OldCallingConv::C : return CallingConv::C;
1289 case OldCallingConv::CSRet : return CallingConv::C;
1290 case OldCallingConv::Fast : return CallingConv::Fast;
1291 case OldCallingConv::Cold : return CallingConv::Cold;
1292 case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1293 case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1299 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1300 bool debug, bool addAttrs)
1303 CurFilename = infile;
1306 AddAttributes = addAttrs;
1307 ObsoleteVarArgs = false;
1310 CurModule.CurrentModule = new Module(CurFilename);
1312 // Check to make sure the parser succeeded
1315 delete ParserResult;
1316 std::cerr << "llvm-upgrade: parse failed.\n";
1320 // Check to make sure that parsing produced a result
1321 if (!ParserResult) {
1322 std::cerr << "llvm-upgrade: no parse result.\n";
1326 // Reset ParserResult variable while saving its value for the result.
1327 Module *Result = ParserResult;
1330 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1333 if ((F = Result->getFunction("llvm.va_start"))
1334 && F->getFunctionType()->getNumParams() == 0)
1335 ObsoleteVarArgs = true;
1336 if((F = Result->getFunction("llvm.va_copy"))
1337 && F->getFunctionType()->getNumParams() == 1)
1338 ObsoleteVarArgs = true;
1341 if (ObsoleteVarArgs && NewVarArgs) {
1342 error("This file is corrupt: it uses both new and old style varargs");
1346 if(ObsoleteVarArgs) {
1347 if(Function* F = Result->getFunction("llvm.va_start")) {
1348 if (F->arg_size() != 0) {
1349 error("Obsolete va_start takes 0 argument");
1355 //bar = alloca typeof(foo)
1359 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1360 const Type* ArgTy = F->getFunctionType()->getReturnType();
1361 const Type* ArgTyPtr = PointerType::get(ArgTy);
1362 Function* NF = cast<Function>(Result->getOrInsertFunction(
1363 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1365 while (!F->use_empty()) {
1366 CallInst* CI = cast<CallInst>(F->use_back());
1367 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1368 new CallInst(NF, bar, "", CI);
1369 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1370 CI->replaceAllUsesWith(foo);
1371 CI->getParent()->getInstList().erase(CI);
1373 Result->getFunctionList().erase(F);
1376 if(Function* F = Result->getFunction("llvm.va_end")) {
1377 if(F->arg_size() != 1) {
1378 error("Obsolete va_end takes 1 argument");
1384 //bar = alloca 1 of typeof(foo)
1386 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1387 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1388 const Type* ArgTyPtr = PointerType::get(ArgTy);
1389 Function* NF = cast<Function>(Result->getOrInsertFunction(
1390 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1392 while (!F->use_empty()) {
1393 CallInst* CI = cast<CallInst>(F->use_back());
1394 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1395 new StoreInst(CI->getOperand(1), bar, CI);
1396 new CallInst(NF, bar, "", CI);
1397 CI->getParent()->getInstList().erase(CI);
1399 Result->getFunctionList().erase(F);
1402 if(Function* F = Result->getFunction("llvm.va_copy")) {
1403 if(F->arg_size() != 1) {
1404 error("Obsolete va_copy takes 1 argument");
1409 //a = alloca 1 of typeof(foo)
1410 //b = alloca 1 of typeof(foo)
1415 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1416 const Type* ArgTy = F->getFunctionType()->getReturnType();
1417 const Type* ArgTyPtr = PointerType::get(ArgTy);
1418 Function* NF = cast<Function>(Result->getOrInsertFunction(
1419 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1421 while (!F->use_empty()) {
1422 CallInst* CI = cast<CallInst>(F->use_back());
1423 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1424 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1425 new StoreInst(CI->getOperand(1), b, CI);
1426 new CallInst(NF, a, b, "", CI);
1427 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1428 CI->replaceAllUsesWith(foo);
1429 CI->getParent()->getInstList().erase(CI);
1431 Result->getFunctionList().erase(F);
1438 } // end llvm namespace
1440 using namespace llvm;
1445 llvm::Module *ModuleVal;
1446 llvm::Function *FunctionVal;
1447 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1448 llvm::BasicBlock *BasicBlockVal;
1449 llvm::TerminatorInst *TermInstVal;
1450 llvm::InstrInfo InstVal;
1451 llvm::ConstInfo ConstVal;
1452 llvm::ValueInfo ValueVal;
1453 llvm::PATypeInfo TypeVal;
1454 llvm::TypeInfo PrimType;
1455 llvm::PHIListInfo PHIList;
1456 std::list<llvm::PATypeInfo> *TypeList;
1457 std::vector<llvm::ValueInfo> *ValueList;
1458 std::vector<llvm::ConstInfo> *ConstVector;
1461 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1462 // Represent the RHS of PHI node
1463 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1465 llvm::GlobalValue::LinkageTypes Linkage;
1473 char *StrVal; // This memory is strdup'd!
1474 llvm::ValID ValIDVal; // strdup'd memory maybe!
1476 llvm::BinaryOps BinaryOpVal;
1477 llvm::TermOps TermOpVal;
1478 llvm::MemoryOps MemOpVal;
1479 llvm::OtherOps OtherOpVal;
1480 llvm::CastOps CastOpVal;
1481 llvm::ICmpInst::Predicate IPred;
1482 llvm::FCmpInst::Predicate FPred;
1483 llvm::Module::Endianness Endianness;
1486 %type <ModuleVal> Module FunctionList
1487 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1488 %type <BasicBlockVal> BasicBlock InstructionList
1489 %type <TermInstVal> BBTerminatorInst
1490 %type <InstVal> Inst InstVal MemoryInst
1491 %type <ConstVal> ConstVal ConstExpr
1492 %type <ConstVector> ConstVector
1493 %type <ArgList> ArgList ArgListH
1494 %type <ArgVal> ArgVal
1495 %type <PHIList> PHIList
1496 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1497 %type <ValueList> IndexList // For GEP derived indices
1498 %type <TypeList> TypeListI ArgTypeListI
1499 %type <JumpTable> JumpTable
1500 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1501 %type <BoolVal> OptVolatile // 'volatile' or not
1502 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1503 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1504 %type <Linkage> OptLinkage FnDeclareLinkage
1505 %type <Endianness> BigOrLittle
1507 // ValueRef - Unresolved reference to a definition or BB
1508 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1509 %type <ValueVal> ResolvedVal // <type> <valref> pair
1511 // Tokens and types for handling constant integer values
1513 // ESINT64VAL - A negative number within long long range
1514 %token <SInt64Val> ESINT64VAL
1516 // EUINT64VAL - A positive number within uns. long long range
1517 %token <UInt64Val> EUINT64VAL
1518 %type <SInt64Val> EINT64VAL
1520 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1521 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1522 %type <SIntVal> INTVAL
1523 %token <FPVal> FPVAL // Float or Double constant
1525 // Built in types...
1526 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1527 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1528 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1529 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1531 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1532 %type <StrVal> Name OptName OptAssign
1533 %type <UIntVal> OptAlign OptCAlign
1534 %type <StrVal> OptSection SectionString
1536 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1537 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1538 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1539 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1540 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1541 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1542 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1543 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1545 %type <UIntVal> OptCallingConv
1547 // Basic Block Terminating Operators
1548 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1549 %token UNWIND EXCEPT
1552 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1553 %type <BinaryOpVal> ShiftOps
1554 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1555 %token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR
1556 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1557 %token <OtherOpVal> ICMP FCMP
1559 // Memory Instructions
1560 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1563 %token <OtherOpVal> PHI_TOK SELECT VAARG
1564 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1565 %token VAARG_old VANEXT_old //OBSOLETE
1567 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1568 %type <IPred> IPredicates
1569 %type <FPred> FPredicates
1570 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1571 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1573 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1574 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1575 %type <CastOpVal> CastOps
1581 // Handle constant integer size restriction and conversion...
1586 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1587 error("Value too large for type");
1593 : ESINT64VAL // These have same type and can't cause problems...
1595 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1596 error("Value too large for type");
1600 // Operations that are notably excluded from this list include:
1601 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1604 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1612 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1616 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1617 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1618 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1619 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1620 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1624 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1625 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1626 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1627 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1628 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1629 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1630 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1631 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1632 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1635 : SHL | SHR | ASHR | LSHR
1639 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1640 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1643 // These are some types that allow classification if we only want a particular
1644 // thing... for example, only a signed, unsigned, or integral type.
1646 : LONG | INT | SHORT | SBYTE
1650 : ULONG | UINT | USHORT | UBYTE
1654 : SIntType | UIntType
1661 // OptAssign - Value producing statements have an optional assignment component
1671 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1672 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1673 | WEAK { $$ = GlobalValue::WeakLinkage; }
1674 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1675 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1676 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1677 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1678 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1682 : /*empty*/ { $$ = OldCallingConv::C; }
1683 | CCC_TOK { $$ = OldCallingConv::C; }
1684 | CSRETCC_TOK { $$ = OldCallingConv::CSRet; }
1685 | FASTCC_TOK { $$ = OldCallingConv::Fast; }
1686 | COLDCC_TOK { $$ = OldCallingConv::Cold; }
1687 | X86_STDCALLCC_TOK { $$ = OldCallingConv::X86_StdCall; }
1688 | X86_FASTCALLCC_TOK { $$ = OldCallingConv::X86_FastCall; }
1689 | CC_TOK EUINT64VAL {
1690 if ((unsigned)$2 != $2)
1691 error("Calling conv too large");
1696 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1697 // a comma before it.
1699 : /*empty*/ { $$ = 0; }
1700 | ALIGN EUINT64VAL {
1702 if ($$ != 0 && !isPowerOf2_32($$))
1703 error("Alignment must be a power of two");
1708 : /*empty*/ { $$ = 0; }
1709 | ',' ALIGN EUINT64VAL {
1711 if ($$ != 0 && !isPowerOf2_32($$))
1712 error("Alignment must be a power of two");
1717 : SECTION STRINGCONSTANT {
1718 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1719 if ($2[i] == '"' || $2[i] == '\\')
1720 error("Invalid character in section name");
1726 : /*empty*/ { $$ = 0; }
1727 | SectionString { $$ = $1; }
1730 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1731 // is set to be the global we are processing.
1735 | ',' GlobalVarAttribute GlobalVarAttributes {}
1740 CurGV->setSection($1);
1743 | ALIGN EUINT64VAL {
1744 if ($2 != 0 && !isPowerOf2_32($2))
1745 error("Alignment must be a power of two");
1746 CurGV->setAlignment($2);
1751 //===----------------------------------------------------------------------===//
1752 // Types includes all predefined types... except void, because it can only be
1753 // used in specific contexts (function returning void for example). To have
1754 // access to it, a user must explicitly use TypesV.
1757 // TypesV includes all of 'Types', but it also includes the void type.
1761 $$.PAT = new PATypeHolder($1.T);
1769 $$.PAT = new PATypeHolder($1.T);
1776 if (!UpRefs.empty())
1777 error("Invalid upreference in type: " + (*$1.PAT)->getDescription());
1783 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1784 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1787 // Derived types are added later...
1790 $$.PAT = new PATypeHolder($1.T);
1794 $$.PAT = new PATypeHolder(OpaqueType::get());
1797 | SymbolicValueRef { // Named types are also simple types...
1798 const Type* tmp = getType($1);
1799 $$.PAT = new PATypeHolder(tmp);
1800 $$.S = Signless; // FIXME: what if its signed?
1802 | '\\' EUINT64VAL { // Type UpReference
1803 if ($2 > (uint64_t)~0U)
1804 error("Value out of range");
1805 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1806 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1807 $$.PAT = new PATypeHolder(OT);
1809 UR_OUT("New Upreference!\n");
1811 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1812 std::vector<const Type*> Params;
1813 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1814 E = $3->end(); I != E; ++I) {
1815 Params.push_back(I->PAT->get());
1817 FunctionType::ParamAttrsList ParamAttrs;
1818 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1819 if (isVarArg) Params.pop_back();
1821 $$.PAT = new PATypeHolder(
1822 HandleUpRefs(FunctionType::get($1.PAT->get(), Params, isVarArg,
1825 delete $1.PAT; // Delete the return type handle
1826 delete $3; // Delete the argument list
1828 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1829 $$.PAT = new PATypeHolder(HandleUpRefs(ArrayType::get($4.PAT->get(),
1834 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1835 const llvm::Type* ElemTy = $4.PAT->get();
1836 if ((unsigned)$2 != $2)
1837 error("Unsigned result not equal to signed result");
1838 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1839 error("Elements of a PackedType must be integer or floating point");
1840 if (!isPowerOf2_32($2))
1841 error("PackedType length should be a power of 2");
1842 $$.PAT = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy,
1847 | '{' TypeListI '}' { // Structure type?
1848 std::vector<const Type*> Elements;
1849 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1850 E = $2->end(); I != E; ++I)
1851 Elements.push_back(I->PAT->get());
1852 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1856 | '{' '}' { // Empty structure type?
1857 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1860 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
1861 std::vector<const Type*> Elements;
1862 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1863 E = $3->end(); I != E; ++I) {
1864 Elements.push_back(I->PAT->get());
1867 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1871 | '<' '{' '}' '>' { // Empty packed structure type?
1872 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1875 | UpRTypes '*' { // Pointer type?
1876 if ($1.PAT->get() == Type::LabelTy)
1877 error("Cannot form a pointer to a basic block");
1878 $$.PAT = new PATypeHolder(HandleUpRefs(PointerType::get($1.PAT->get())));
1884 // TypeList - Used for struct declarations and as a basis for function type
1885 // declaration type lists
1889 $$ = new std::list<PATypeInfo>();
1892 | TypeListI ',' UpRTypes {
1893 ($$=$1)->push_back($3);
1897 // ArgTypeList - List of types for a function type declaration...
1900 | TypeListI ',' DOTDOTDOT {
1902 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
1903 VoidTI.S = Signless;
1904 ($$=$1)->push_back(VoidTI);
1907 $$ = new std::list<PATypeInfo>();
1909 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
1910 VoidTI.S = Signless;
1911 $$->push_back(VoidTI);
1914 $$ = new std::list<PATypeInfo>();
1918 // ConstVal - The various declarations that go into the constant pool. This
1919 // production is used ONLY to represent constants that show up AFTER a 'const',
1920 // 'constant' or 'global' token at global scope. Constants that can be inlined
1921 // into other expressions (such as integers and constexprs) are handled by the
1922 // ResolvedVal, ValueRef and ConstValueRef productions.
1925 : Types '[' ConstVector ']' { // Nonempty unsized arr
1926 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1928 error("Cannot make array constant with type: '" +
1929 $1.PAT->get()->getDescription() + "'");
1930 const Type *ETy = ATy->getElementType();
1931 int NumElements = ATy->getNumElements();
1933 // Verify that we have the correct size...
1934 if (NumElements != -1 && NumElements != (int)$3->size())
1935 error("Type mismatch: constant sized array initialized with " +
1936 utostr($3->size()) + " arguments, but has size of " +
1937 itostr(NumElements) + "");
1939 // Verify all elements are correct type!
1940 std::vector<Constant*> Elems;
1941 for (unsigned i = 0; i < $3->size(); i++) {
1942 Constant *C = (*$3)[i].C;
1943 const Type* ValTy = C->getType();
1945 error("Element #" + utostr(i) + " is not of type '" +
1946 ETy->getDescription() +"' as required!\nIt is of type '"+
1947 ValTy->getDescription() + "'");
1950 $$.C = ConstantArray::get(ATy, Elems);
1956 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1958 error("Cannot make array constant with type: '" +
1959 $1.PAT->get()->getDescription() + "'");
1960 int NumElements = ATy->getNumElements();
1961 if (NumElements != -1 && NumElements != 0)
1962 error("Type mismatch: constant sized array initialized with 0"
1963 " arguments, but has size of " + itostr(NumElements) +"");
1964 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1968 | Types 'c' STRINGCONSTANT {
1969 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1971 error("Cannot make array constant with type: '" +
1972 $1.PAT->get()->getDescription() + "'");
1973 int NumElements = ATy->getNumElements();
1974 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1975 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1976 error("String arrays require type i8, not '" + ETy->getDescription() +
1978 char *EndStr = UnEscapeLexed($3, true);
1979 if (NumElements != -1 && NumElements != (EndStr-$3))
1980 error("Can't build string constant of size " +
1981 itostr((int)(EndStr-$3)) + " when array has size " +
1982 itostr(NumElements) + "");
1983 std::vector<Constant*> Vals;
1984 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
1985 Vals.push_back(ConstantInt::get(ETy, *C));
1987 $$.C = ConstantArray::get(ATy, Vals);
1991 | Types '<' ConstVector '>' { // Nonempty unsized arr
1992 const PackedType *PTy = dyn_cast<PackedType>($1.PAT->get());
1994 error("Cannot make packed constant with type: '" +
1995 $1.PAT->get()->getDescription() + "'");
1996 const Type *ETy = PTy->getElementType();
1997 int NumElements = PTy->getNumElements();
1998 // Verify that we have the correct size...
1999 if (NumElements != -1 && NumElements != (int)$3->size())
2000 error("Type mismatch: constant sized packed initialized with " +
2001 utostr($3->size()) + " arguments, but has size of " +
2002 itostr(NumElements) + "");
2003 // Verify all elements are correct type!
2004 std::vector<Constant*> Elems;
2005 for (unsigned i = 0; i < $3->size(); i++) {
2006 Constant *C = (*$3)[i].C;
2007 const Type* ValTy = C->getType();
2009 error("Element #" + utostr(i) + " is not of type '" +
2010 ETy->getDescription() +"' as required!\nIt is of type '"+
2011 ValTy->getDescription() + "'");
2014 $$.C = ConstantPacked::get(PTy, Elems);
2019 | Types '{' ConstVector '}' {
2020 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2022 error("Cannot make struct constant with type: '" +
2023 $1.PAT->get()->getDescription() + "'");
2024 if ($3->size() != STy->getNumContainedTypes())
2025 error("Illegal number of initializers for structure type");
2027 // Check to ensure that constants are compatible with the type initializer!
2028 std::vector<Constant*> Fields;
2029 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2030 Constant *C = (*$3)[i].C;
2031 if (C->getType() != STy->getElementType(i))
2032 error("Expected type '" + STy->getElementType(i)->getDescription() +
2033 "' for element #" + utostr(i) + " of structure initializer");
2034 Fields.push_back(C);
2036 $$.C = ConstantStruct::get(STy, Fields);
2042 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2044 error("Cannot make struct constant with type: '" +
2045 $1.PAT->get()->getDescription() + "'");
2046 if (STy->getNumContainedTypes() != 0)
2047 error("Illegal number of initializers for structure type");
2048 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2052 | Types '<' '{' ConstVector '}' '>' {
2053 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2055 error("Cannot make packed struct constant with type: '" +
2056 $1.PAT->get()->getDescription() + "'");
2057 if ($4->size() != STy->getNumContainedTypes())
2058 error("Illegal number of initializers for packed structure type");
2060 // Check to ensure that constants are compatible with the type initializer!
2061 std::vector<Constant*> Fields;
2062 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2063 Constant *C = (*$4)[i].C;
2064 if (C->getType() != STy->getElementType(i))
2065 error("Expected type '" + STy->getElementType(i)->getDescription() +
2066 "' for element #" + utostr(i) + " of packed struct initializer");
2067 Fields.push_back(C);
2069 $$.C = ConstantStruct::get(STy, Fields);
2074 | Types '<' '{' '}' '>' {
2075 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2077 error("Cannot make packed struct constant with type: '" +
2078 $1.PAT->get()->getDescription() + "'");
2079 if (STy->getNumContainedTypes() != 0)
2080 error("Illegal number of initializers for packed structure type");
2081 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2086 const PointerType *PTy = dyn_cast<PointerType>($1.PAT->get());
2088 error("Cannot make null pointer constant with type: '" +
2089 $1.PAT->get()->getDescription() + "'");
2090 $$.C = ConstantPointerNull::get(PTy);
2095 $$.C = UndefValue::get($1.PAT->get());
2099 | Types SymbolicValueRef {
2100 const PointerType *Ty = dyn_cast<PointerType>($1.PAT->get());
2102 error("Global const reference must be a pointer type, not" +
2103 $1.PAT->get()->getDescription());
2105 // ConstExprs can exist in the body of a function, thus creating
2106 // GlobalValues whenever they refer to a variable. Because we are in
2107 // the context of a function, getExistingValue will search the functions
2108 // symbol table instead of the module symbol table for the global symbol,
2109 // which throws things all off. To get around this, we just tell
2110 // getExistingValue that we are at global scope here.
2112 Function *SavedCurFn = CurFun.CurrentFunction;
2113 CurFun.CurrentFunction = 0;
2114 Value *V = getExistingValue(Ty, $2);
2115 CurFun.CurrentFunction = SavedCurFn;
2117 // If this is an initializer for a constant pointer, which is referencing a
2118 // (currently) undefined variable, create a stub now that shall be replaced
2119 // in the future with the right type of variable.
2122 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2123 const PointerType *PT = cast<PointerType>(Ty);
2125 // First check to see if the forward references value is already created!
2126 PerModuleInfo::GlobalRefsType::iterator I =
2127 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2129 if (I != CurModule.GlobalRefs.end()) {
2130 V = I->second; // Placeholder already exists, use it...
2134 if ($2.Type == ValID::NameVal) Name = $2.Name;
2136 // Create the forward referenced global.
2138 if (const FunctionType *FTy =
2139 dyn_cast<FunctionType>(PT->getElementType())) {
2140 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2141 CurModule.CurrentModule);
2143 GV = new GlobalVariable(PT->getElementType(), false,
2144 GlobalValue::ExternalLinkage, 0,
2145 Name, CurModule.CurrentModule);
2148 // Keep track of the fact that we have a forward ref to recycle it
2149 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2153 $$.C = cast<GlobalValue>(V);
2155 delete $1.PAT; // Free the type handle
2158 if ($1.PAT->get() != $2.C->getType())
2159 error("Mismatched types for constant expression");
2164 | Types ZEROINITIALIZER {
2165 const Type *Ty = $1.PAT->get();
2166 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2167 error("Cannot create a null initialized value of this type");
2168 $$.C = Constant::getNullValue(Ty);
2172 | SIntType EINT64VAL { // integral constants
2173 const Type *Ty = $1.T;
2174 if (!ConstantInt::isValueValidForType(Ty, $2))
2175 error("Constant value doesn't fit in type");
2176 $$.C = ConstantInt::get(Ty, $2);
2179 | UIntType EUINT64VAL { // integral constants
2180 const Type *Ty = $1.T;
2181 if (!ConstantInt::isValueValidForType(Ty, $2))
2182 error("Constant value doesn't fit in type");
2183 $$.C = ConstantInt::get(Ty, $2);
2186 | BOOL TRUETOK { // Boolean constants
2187 $$.C = ConstantInt::get(Type::Int1Ty, true);
2190 | BOOL FALSETOK { // Boolean constants
2191 $$.C = ConstantInt::get(Type::Int1Ty, false);
2194 | FPType FPVAL { // Float & Double constants
2195 if (!ConstantFP::isValueValidForType($1.T, $2))
2196 error("Floating point constant invalid for type");
2197 $$.C = ConstantFP::get($1.T, $2);
2203 : CastOps '(' ConstVal TO Types ')' {
2204 const Type* SrcTy = $3.C->getType();
2205 const Type* DstTy = $5.PAT->get();
2206 Signedness SrcSign = $3.S;
2207 Signedness DstSign = $5.S;
2208 if (!SrcTy->isFirstClassType())
2209 error("cast constant expression from a non-primitive type: '" +
2210 SrcTy->getDescription() + "'");
2211 if (!DstTy->isFirstClassType())
2212 error("cast constant expression to a non-primitive type: '" +
2213 DstTy->getDescription() + "'");
2214 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2218 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2219 const Type *Ty = $3.C->getType();
2220 if (!isa<PointerType>(Ty))
2221 error("GetElementPtr requires a pointer operand");
2223 std::vector<Value*> VIndices;
2224 std::vector<Constant*> CIndices;
2225 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2228 $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2231 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2232 if (!$3.C->getType()->isInteger() ||
2233 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2234 error("Select condition must be bool type");
2235 if ($5.C->getType() != $7.C->getType())
2236 error("Select operand types must match");
2237 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2240 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2241 const Type *Ty = $3.C->getType();
2242 if (Ty != $5.C->getType())
2243 error("Binary operator types must match");
2244 // First, make sure we're dealing with the right opcode by upgrading from
2245 // obsolete versions.
2246 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2248 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2249 // To retain backward compatibility with these early compilers, we emit a
2250 // cast to the appropriate integer type automatically if we are in the
2251 // broken case. See PR424 for more information.
2252 if (!isa<PointerType>(Ty)) {
2253 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2255 const Type *IntPtrTy = 0;
2256 switch (CurModule.CurrentModule->getPointerSize()) {
2257 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2258 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2259 default: error("invalid pointer binary constant expr");
2261 $$.C = ConstantExpr::get(Opcode,
2262 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2263 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2264 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2268 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2269 const Type* Ty = $3.C->getType();
2270 if (Ty != $5.C->getType())
2271 error("Logical operator types must match");
2272 if (!Ty->isInteger()) {
2273 if (!isa<PackedType>(Ty) ||
2274 !cast<PackedType>(Ty)->getElementType()->isInteger())
2275 error("Logical operator requires integer operands");
2277 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2278 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2281 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2282 const Type* Ty = $3.C->getType();
2283 if (Ty != $5.C->getType())
2284 error("setcc operand types must match");
2285 unsigned short pred;
2286 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2287 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2290 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2291 if ($4.C->getType() != $6.C->getType())
2292 error("icmp operand types must match");
2293 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2296 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2297 if ($4.C->getType() != $6.C->getType())
2298 error("fcmp operand types must match");
2299 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2302 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2303 if (!$5.C->getType()->isInteger() ||
2304 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2305 error("Shift count for shift constant must be unsigned byte");
2306 const Type* Ty = $3.C->getType();
2307 if (!$3.C->getType()->isInteger())
2308 error("Shift constant expression requires integer operand");
2309 Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2310 $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
2313 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2314 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2315 error("Invalid extractelement operands");
2316 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2319 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2320 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2321 error("Invalid insertelement operands");
2322 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2325 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2326 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2327 error("Invalid shufflevector operands");
2328 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2334 // ConstVector - A list of comma separated constants.
2336 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2338 $$ = new std::vector<ConstInfo>();
2344 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2346 : GLOBAL { $$ = false; }
2347 | CONSTANT { $$ = true; }
2351 //===----------------------------------------------------------------------===//
2352 // Rules to match Modules
2353 //===----------------------------------------------------------------------===//
2355 // Module rule: Capture the result of parsing the whole file into a result
2360 $$ = ParserResult = $1;
2361 CurModule.ModuleDone();
2365 // FunctionList - A list of functions, preceeded by a constant pool.
2368 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2369 | FunctionList FunctionProto { $$ = $1; }
2370 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2371 | FunctionList IMPLEMENTATION { $$ = $1; }
2373 $$ = CurModule.CurrentModule;
2374 // Emit an error if there are any unresolved types left.
2375 if (!CurModule.LateResolveTypes.empty()) {
2376 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2377 if (DID.Type == ValID::NameVal) {
2378 error("Reference to an undefined type: '"+DID.getName() + "'");
2380 error("Reference to an undefined type: #" + itostr(DID.Num));
2386 // ConstPool - Constants with optional names assigned to them.
2388 : ConstPool OptAssign TYPE TypesV {
2389 // Eagerly resolve types. This is not an optimization, this is a
2390 // requirement that is due to the fact that we could have this:
2392 // %list = type { %list * }
2393 // %list = type { %list * } ; repeated type decl
2395 // If types are not resolved eagerly, then the two types will not be
2396 // determined to be the same type!
2398 const Type* Ty = $4.PAT->get();
2399 ResolveTypeTo($2, Ty);
2401 if (!setTypeName(Ty, $2) && !$2) {
2402 // If this is a named type that is not a redefinition, add it to the slot
2404 CurModule.Types.push_back(Ty);
2408 | ConstPool FunctionProto { // Function prototypes can be in const pool
2410 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2412 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2414 error("Global value initializer is not a constant");
2415 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2416 } GlobalVarAttributes {
2419 | ConstPool OptAssign EXTERNAL GlobalType Types {
2420 const Type *Ty = $5.PAT->get();
2421 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2423 } GlobalVarAttributes {
2426 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2427 const Type *Ty = $5.PAT->get();
2428 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2430 } GlobalVarAttributes {
2433 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2434 const Type *Ty = $5.PAT->get();
2436 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2438 } GlobalVarAttributes {
2441 | ConstPool TARGET TargetDefinition {
2443 | ConstPool DEPLIBS '=' LibrariesDefinition {
2445 | /* empty: end of list */ {
2451 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2452 char *EndStr = UnEscapeLexed($1, true);
2453 std::string NewAsm($1, EndStr);
2456 if (AsmSoFar.empty())
2457 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2459 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2464 : BIG { $$ = Module::BigEndian; }
2465 | LITTLE { $$ = Module::LittleEndian; }
2469 : ENDIAN '=' BigOrLittle {
2470 CurModule.setEndianness($3);
2472 | POINTERSIZE '=' EUINT64VAL {
2474 CurModule.setPointerSize(Module::Pointer32);
2476 CurModule.setPointerSize(Module::Pointer64);
2478 error("Invalid pointer size: '" + utostr($3) + "'");
2480 | TRIPLE '=' STRINGCONSTANT {
2481 CurModule.CurrentModule->setTargetTriple($3);
2484 | DATALAYOUT '=' STRINGCONSTANT {
2485 CurModule.CurrentModule->setDataLayout($3);
2495 : LibList ',' STRINGCONSTANT {
2496 CurModule.CurrentModule->addLibrary($3);
2500 CurModule.CurrentModule->addLibrary($1);
2503 | /* empty: end of list */ { }
2506 //===----------------------------------------------------------------------===//
2507 // Rules to match Function Headers
2508 //===----------------------------------------------------------------------===//
2511 : VAR_ID | STRINGCONSTANT
2516 | /*empty*/ { $$ = 0; }
2521 if ($1.PAT->get() == Type::VoidTy)
2522 error("void typed arguments are invalid");
2523 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2528 : ArgListH ',' ArgVal {
2534 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2541 : ArgListH { $$ = $1; }
2542 | ArgListH ',' DOTDOTDOT {
2545 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2546 VoidTI.S = Signless;
2547 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2550 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2552 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2553 VoidTI.S = Signless;
2554 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2556 | /* empty */ { $$ = 0; }
2560 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2562 std::string FunctionName($3);
2563 free($3); // Free strdup'd memory!
2565 const Type* RetTy = $2.PAT->get();
2567 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2568 error("LLVM functions cannot return aggregate types");
2570 std::vector<const Type*> ParamTyList;
2572 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2573 // i8*. We check here for those names and override the parameter list
2574 // types to ensure the prototype is correct.
2575 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2576 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2577 } else if (FunctionName == "llvm.va_copy") {
2578 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2579 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2580 } else if ($5) { // If there are arguments...
2581 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2582 I = $5->begin(), E = $5->end(); I != E; ++I) {
2583 const Type *Ty = I->first.PAT->get();
2584 ParamTyList.push_back(Ty);
2588 bool isVarArg = ParamTyList.size() && ParamTyList.back() == Type::VoidTy;
2590 ParamTyList.pop_back();
2592 // Convert the CSRet calling convention into the corresponding parameter
2594 FunctionType::ParamAttrsList ParamAttrs;
2595 if ($1 == OldCallingConv::CSRet) {
2596 ParamAttrs.push_back(FunctionType::NoAttributeSet); // result
2597 ParamAttrs.push_back(FunctionType::StructRetAttribute); // first arg
2600 const FunctionType *FT = FunctionType::get(RetTy, ParamTyList, isVarArg,
2602 const PointerType *PFT = PointerType::get(FT);
2606 if (!FunctionName.empty()) {
2607 ID = ValID::create((char*)FunctionName.c_str());
2609 ID = ValID::create((int)CurModule.Values[PFT].size());
2613 Module* M = CurModule.CurrentModule;
2615 // See if this function was forward referenced. If so, recycle the object.
2616 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2617 // Move the function to the end of the list, from whereever it was
2618 // previously inserted.
2619 Fn = cast<Function>(FWRef);
2620 M->getFunctionList().remove(Fn);
2621 M->getFunctionList().push_back(Fn);
2622 } else if (!FunctionName.empty()) {
2623 GlobalValue *Conflict = M->getFunction(FunctionName);
2625 Conflict = M->getNamedGlobal(FunctionName);
2626 if (Conflict && PFT == Conflict->getType()) {
2627 if (!CurFun.isDeclare && !Conflict->isDeclaration()) {
2628 // We have two function definitions that conflict, same type, same
2629 // name. We should really check to make sure that this is the result
2630 // of integer type planes collapsing and generate an error if it is
2631 // not, but we'll just rename on the assumption that it is. However,
2632 // let's do it intelligently and rename the internal linkage one
2634 std::string NewName(makeNameUnique(FunctionName));
2635 if (Conflict->hasInternalLinkage()) {
2636 Conflict->setName(NewName);
2637 RenameMapKey Key = std::make_pair(FunctionName,Conflict->getType());
2638 CurModule.RenameMap[Key] = NewName;
2639 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2640 InsertValue(Fn, CurModule.Values);
2642 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2643 InsertValue(Fn, CurModule.Values);
2644 RenameMapKey Key = std::make_pair(FunctionName,PFT);
2645 CurModule.RenameMap[Key] = NewName;
2648 // If they are not both definitions, then just use the function we
2649 // found since the types are the same.
2650 Fn = cast<Function>(Conflict);
2652 // Make sure to strip off any argument names so we can't get
2654 if (Fn->isDeclaration())
2655 for (Function::arg_iterator AI = Fn->arg_begin(),
2656 AE = Fn->arg_end(); AI != AE; ++AI)
2659 } else if (Conflict) {
2660 // We have two globals with the same name and different types.
2661 // Previously, this was permitted because the symbol table had
2662 // "type planes" and names only needed to be distinct within a
2663 // type plane. After PR411 was fixed, this is no loner the case.
2664 // To resolve this we must rename one of the two.
2665 if (Conflict->hasInternalLinkage()) {
2666 // We can safely renamed the Conflict.
2667 Conflict->setName(makeNameUnique(Conflict->getName()));
2668 RenameMapKey Key = std::make_pair(FunctionName,Conflict->getType());
2669 CurModule.RenameMap[Key] = Conflict->getName();
2670 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2671 InsertValue(Fn, CurModule.Values);
2672 } else if (CurFun.Linkage == GlobalValue::InternalLinkage) {
2673 // We can safely rename the function we're defining
2674 std::string NewName = makeNameUnique(FunctionName);
2675 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2676 InsertValue(Fn, CurModule.Values);
2677 RenameMapKey Key = std::make_pair(FunctionName,PFT);
2678 CurModule.RenameMap[Key] = NewName;
2680 // We can't quietly rename either of these things, but we must
2681 // rename one of them. Generate a warning about the renaming and
2682 // elect to rename the thing we're now defining.
2683 std::string NewName = makeNameUnique(FunctionName);
2684 warning("Renaming function '" + FunctionName + "' as '" + NewName +
2685 "' may cause linkage errors");
2686 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2687 InsertValue(Fn, CurModule.Values);
2688 RenameMapKey Key = std::make_pair(FunctionName,PFT);
2689 CurModule.RenameMap[Key] = NewName;
2692 // There's no conflict, just define the function
2693 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2694 InsertValue(Fn, CurModule.Values);
2698 CurFun.FunctionStart(Fn);
2700 if (CurFun.isDeclare) {
2701 // If we have declaration, always overwrite linkage. This will allow us
2702 // to correctly handle cases, when pointer to function is passed as
2703 // argument to another function.
2704 Fn->setLinkage(CurFun.Linkage);
2706 Fn->setCallingConv(upgradeCallingConv($1));
2707 Fn->setAlignment($8);
2713 // Add all of the arguments we parsed to the function...
2714 if ($5) { // Is null if empty...
2715 if (isVarArg) { // Nuke the last entry
2716 assert($5->back().first.PAT->get() == Type::VoidTy &&
2717 $5->back().second == 0 && "Not a varargs marker");
2718 delete $5->back().first.PAT;
2719 $5->pop_back(); // Delete the last entry
2721 Function::arg_iterator ArgIt = Fn->arg_begin();
2722 Function::arg_iterator ArgEnd = Fn->arg_end();
2723 std::vector<std::pair<PATypeInfo,char*> >::iterator I = $5->begin();
2724 std::vector<std::pair<PATypeInfo,char*> >::iterator E = $5->end();
2725 for ( ; I != E && ArgIt != ArgEnd; ++I, ++ArgIt) {
2726 delete I->first.PAT; // Delete the typeholder...
2727 setValueName(ArgIt, I->second); // Insert arg into symtab...
2730 delete $5; // We're now done with the argument list
2736 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
2740 : OptLinkage FunctionHeaderH BEGIN {
2741 $$ = CurFun.CurrentFunction;
2743 // Make sure that we keep track of the linkage type even if there was a
2744 // previous "declare".
2750 : ENDTOK | '}' // Allow end of '}' to end a function
2754 : BasicBlockList END {
2759 : /*default*/ { $$ = GlobalValue::ExternalLinkage; }
2760 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
2761 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
2765 : DECLARE { CurFun.isDeclare = true; }
2766 FnDeclareLinkage { CurFun.Linkage = $3; } FunctionHeaderH {
2767 $$ = CurFun.CurrentFunction;
2768 CurFun.FunctionDone();
2773 //===----------------------------------------------------------------------===//
2774 // Rules to match Basic Blocks
2775 //===----------------------------------------------------------------------===//
2778 : /* empty */ { $$ = false; }
2779 | SIDEEFFECT { $$ = true; }
2783 // A reference to a direct constant
2784 : ESINT64VAL { $$ = ValID::create($1); }
2785 | EUINT64VAL { $$ = ValID::create($1); }
2786 | FPVAL { $$ = ValID::create($1); }
2787 | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); }
2788 | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2789 | NULL_TOK { $$ = ValID::createNull(); }
2790 | UNDEF { $$ = ValID::createUndef(); }
2791 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2792 | '<' ConstVector '>' { // Nonempty unsized packed vector
2793 const Type *ETy = (*$2)[0].C->getType();
2794 int NumElements = $2->size();
2795 PackedType* pt = PackedType::get(ETy, NumElements);
2796 PATypeHolder* PTy = new PATypeHolder(
2797 HandleUpRefs(PackedType::get(ETy, NumElements)));
2799 // Verify all elements are correct type!
2800 std::vector<Constant*> Elems;
2801 for (unsigned i = 0; i < $2->size(); i++) {
2802 Constant *C = (*$2)[i].C;
2803 const Type *CTy = C->getType();
2805 error("Element #" + utostr(i) + " is not of type '" +
2806 ETy->getDescription() +"' as required!\nIt is of type '" +
2807 CTy->getDescription() + "'");
2810 $$ = ValID::create(ConstantPacked::get(pt, Elems));
2811 delete PTy; delete $2;
2814 $$ = ValID::create($1.C);
2816 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2817 char *End = UnEscapeLexed($3, true);
2818 std::string AsmStr = std::string($3, End);
2819 End = UnEscapeLexed($5, true);
2820 std::string Constraints = std::string($5, End);
2821 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2827 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2831 : INTVAL { $$ = ValID::create($1); }
2832 | Name { $$ = ValID::create($1); }
2835 // ValueRef - A reference to a definition... either constant or symbolic
2837 : SymbolicValueRef | ConstValueRef
2841 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2842 // type immediately preceeds the value reference, and allows complex constant
2843 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2846 const Type *Ty = $1.PAT->get();
2848 $$.V = getVal(Ty, $2);
2854 : BasicBlockList BasicBlock {
2857 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2862 // Basic blocks are terminated by branching instructions:
2863 // br, br/cc, switch, ret
2866 : InstructionList OptAssign BBTerminatorInst {
2867 setValueName($3, $2);
2869 $1->getInstList().push_back($3);
2876 : InstructionList Inst {
2878 $1->getInstList().push_back($2.I);
2882 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2883 // Make sure to move the basic block to the correct location in the
2884 // function, instead of leaving it inserted wherever it was first
2886 Function::BasicBlockListType &BBL =
2887 CurFun.CurrentFunction->getBasicBlockList();
2888 BBL.splice(BBL.end(), BBL, $$);
2891 $$ = CurBB = getBBVal(ValID::create($1), true);
2892 // Make sure to move the basic block to the correct location in the
2893 // function, instead of leaving it inserted wherever it was first
2895 Function::BasicBlockListType &BBL =
2896 CurFun.CurrentFunction->getBasicBlockList();
2897 BBL.splice(BBL.end(), BBL, $$);
2901 Unwind : UNWIND | EXCEPT;
2904 : RET ResolvedVal { // Return with a result...
2905 $$ = new ReturnInst($2.V);
2907 | RET VOID { // Return with no result...
2908 $$ = new ReturnInst();
2910 | BR LABEL ValueRef { // Unconditional Branch...
2911 BasicBlock* tmpBB = getBBVal($3);
2912 $$ = new BranchInst(tmpBB);
2913 } // Conditional Branch...
2914 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2915 BasicBlock* tmpBBA = getBBVal($6);
2916 BasicBlock* tmpBBB = getBBVal($9);
2917 Value* tmpVal = getVal(Type::Int1Ty, $3);
2918 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2920 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2921 Value* tmpVal = getVal($2.T, $3);
2922 BasicBlock* tmpBB = getBBVal($6);
2923 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2925 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2927 for (; I != E; ++I) {
2928 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2929 S->addCase(CI, I->second);
2931 error("Switch case is constant, but not a simple integer");
2935 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2936 Value* tmpVal = getVal($2.T, $3);
2937 BasicBlock* tmpBB = getBBVal($6);
2938 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2941 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2942 TO LABEL ValueRef Unwind LABEL ValueRef {
2943 const PointerType *PFTy;
2944 const FunctionType *Ty;
2946 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
2947 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2948 // Pull out the types of all of the arguments...
2949 std::vector<const Type*> ParamTypes;
2951 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2953 ParamTypes.push_back((*I).V->getType());
2955 FunctionType::ParamAttrsList ParamAttrs;
2956 if ($2 == OldCallingConv::CSRet) {
2957 ParamAttrs.push_back(FunctionType::NoAttributeSet);
2958 ParamAttrs.push_back(FunctionType::StructRetAttribute);
2960 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2961 if (isVarArg) ParamTypes.pop_back();
2962 Ty = FunctionType::get($3.PAT->get(), ParamTypes, isVarArg, ParamAttrs);
2963 PFTy = PointerType::get(Ty);
2965 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2966 BasicBlock *Normal = getBBVal($10);
2967 BasicBlock *Except = getBBVal($13);
2969 // Create the call node...
2970 if (!$6) { // Has no arguments?
2971 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2972 } else { // Has arguments?
2973 // Loop through FunctionType's arguments and ensure they are specified
2976 FunctionType::param_iterator I = Ty->param_begin();
2977 FunctionType::param_iterator E = Ty->param_end();
2978 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2980 std::vector<Value*> Args;
2981 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2982 if ((*ArgI).V->getType() != *I)
2983 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2984 (*I)->getDescription() + "'");
2985 Args.push_back((*ArgI).V);
2988 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2989 error("Invalid number of parameters detected");
2991 $$ = new InvokeInst(V, Normal, Except, Args);
2993 cast<InvokeInst>($$)->setCallingConv(upgradeCallingConv($2));
2998 $$ = new UnwindInst();
3001 $$ = new UnreachableInst();
3006 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
3008 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
3011 error("May only switch on a constant pool value");
3013 BasicBlock* tmpBB = getBBVal($6);
3014 $$->push_back(std::make_pair(V, tmpBB));
3016 | IntType ConstValueRef ',' LABEL ValueRef {
3017 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3018 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
3021 error("May only switch on a constant pool value");
3023 BasicBlock* tmpBB = getBBVal($5);
3024 $$->push_back(std::make_pair(V, tmpBB));
3029 : OptAssign InstVal {
3032 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
3033 if (BCI->getSrcTy() == BCI->getDestTy() &&
3034 BCI->getOperand(0)->getName() == $1)
3035 // This is a useless bit cast causing a name redefinition. It is
3036 // a bit cast from a type to the same type of an operand with the
3037 // same name as the name we would give this instruction. Since this
3038 // instruction results in no code generation, it is safe to omit
3039 // the instruction. This situation can occur because of collapsed
3040 // type planes. For example:
3041 // %X = add int %Y, %Z
3042 // %X = cast int %Y to uint
3043 // After upgrade, this looks like:
3044 // %X = add i32 %Y, %Z
3045 // %X = bitcast i32 to i32
3046 // The bitcast is clearly useless so we omit it.
3052 setValueName($2.I, $1);
3058 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3059 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3061 Value* tmpVal = getVal($1.PAT->get(), $3);
3062 BasicBlock* tmpBB = getBBVal($5);
3063 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3066 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3068 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3069 BasicBlock* tmpBB = getBBVal($6);
3070 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3074 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3075 $$ = new std::vector<ValueInfo>();
3078 | ValueRefList ',' ResolvedVal {
3083 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
3086 | /*empty*/ { $$ = 0; }
3099 : ArithmeticOps Types ValueRef ',' ValueRef {
3100 const Type* Ty = $2.PAT->get();
3101 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
3102 error("Arithmetic operator requires integer, FP, or packed operands");
3103 if (isa<PackedType>(Ty) &&
3104 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3105 error("Remainder not supported on packed types");
3106 // Upgrade the opcode from obsolete versions before we do anything with it.
3107 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3108 Value* val1 = getVal(Ty, $3);
3109 Value* val2 = getVal(Ty, $5);
3110 $$.I = BinaryOperator::create(Opcode, val1, val2);
3112 error("binary operator returned null");
3116 | LogicalOps Types ValueRef ',' ValueRef {
3117 const Type *Ty = $2.PAT->get();
3118 if (!Ty->isInteger()) {
3119 if (!isa<PackedType>(Ty) ||
3120 !cast<PackedType>(Ty)->getElementType()->isInteger())
3121 error("Logical operator requires integral operands");
3123 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3124 Value* tmpVal1 = getVal(Ty, $3);
3125 Value* tmpVal2 = getVal(Ty, $5);
3126 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3128 error("binary operator returned null");
3132 | SetCondOps Types ValueRef ',' ValueRef {
3133 const Type* Ty = $2.PAT->get();
3134 if(isa<PackedType>(Ty))
3135 error("PackedTypes currently not supported in setcc instructions");
3136 unsigned short pred;
3137 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3138 Value* tmpVal1 = getVal(Ty, $3);
3139 Value* tmpVal2 = getVal(Ty, $5);
3140 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3142 error("binary operator returned null");
3146 | ICMP IPredicates Types ValueRef ',' ValueRef {
3147 const Type *Ty = $3.PAT->get();
3148 if (isa<PackedType>(Ty))
3149 error("PackedTypes currently not supported in icmp instructions");
3150 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3151 error("icmp requires integer or pointer typed operands");
3152 Value* tmpVal1 = getVal(Ty, $4);
3153 Value* tmpVal2 = getVal(Ty, $6);
3154 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3158 | FCMP FPredicates Types ValueRef ',' ValueRef {
3159 const Type *Ty = $3.PAT->get();
3160 if (isa<PackedType>(Ty))
3161 error("PackedTypes currently not supported in fcmp instructions");
3162 else if (!Ty->isFloatingPoint())
3163 error("fcmp instruction requires floating point operands");
3164 Value* tmpVal1 = getVal(Ty, $4);
3165 Value* tmpVal2 = getVal(Ty, $6);
3166 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3171 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3172 const Type *Ty = $2.V->getType();
3173 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3175 error("Expected integral type for not instruction");
3176 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3178 error("Could not create a xor instruction");
3181 | ShiftOps ResolvedVal ',' ResolvedVal {
3182 if (!$4.V->getType()->isInteger() ||
3183 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3184 error("Shift amount must be int8");
3185 const Type* Ty = $2.V->getType();
3186 if (!Ty->isInteger())
3187 error("Shift constant expression requires integer operand");
3188 Value* ShiftAmt = 0;
3189 if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3190 if (Constant *C = dyn_cast<Constant>($4.V))
3191 ShiftAmt = ConstantExpr::getZExt(C, Ty);
3193 ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3196 $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
3199 | CastOps ResolvedVal TO Types {
3200 const Type *DstTy = $4.PAT->get();
3201 if (!DstTy->isFirstClassType())
3202 error("cast instruction to a non-primitive type: '" +
3203 DstTy->getDescription() + "'");
3204 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3208 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3209 if (!$2.V->getType()->isInteger() ||
3210 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3211 error("select condition must be bool");
3212 if ($4.V->getType() != $6.V->getType())
3213 error("select value types should match");
3214 $$.I = new SelectInst($2.V, $4.V, $6.V);
3217 | VAARG ResolvedVal ',' Types {
3218 const Type *Ty = $4.PAT->get();
3220 $$.I = new VAArgInst($2.V, Ty);
3224 | VAARG_old ResolvedVal ',' Types {
3225 const Type* ArgTy = $2.V->getType();
3226 const Type* DstTy = $4.PAT->get();
3227 ObsoleteVarArgs = true;
3228 Function* NF = cast<Function>(CurModule.CurrentModule->
3229 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3232 //foo = alloca 1 of t
3236 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3237 CurBB->getInstList().push_back(foo);
3238 CallInst* bar = new CallInst(NF, $2.V);
3239 CurBB->getInstList().push_back(bar);
3240 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3241 $$.I = new VAArgInst(foo, DstTy);
3245 | VANEXT_old ResolvedVal ',' Types {
3246 const Type* ArgTy = $2.V->getType();
3247 const Type* DstTy = $4.PAT->get();
3248 ObsoleteVarArgs = true;
3249 Function* NF = cast<Function>(CurModule.CurrentModule->
3250 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3252 //b = vanext a, t ->
3253 //foo = alloca 1 of t
3256 //tmp = vaarg foo, t
3258 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3259 CurBB->getInstList().push_back(foo);
3260 CallInst* bar = new CallInst(NF, $2.V);
3261 CurBB->getInstList().push_back(bar);
3262 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3263 Instruction* tmp = new VAArgInst(foo, DstTy);
3264 CurBB->getInstList().push_back(tmp);
3265 $$.I = new LoadInst(foo);
3269 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3270 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3271 error("Invalid extractelement operands");
3272 $$.I = new ExtractElementInst($2.V, $4.V);
3275 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3276 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3277 error("Invalid insertelement operands");
3278 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3281 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3282 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3283 error("Invalid shufflevector operands");
3284 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3288 const Type *Ty = $2.P->front().first->getType();
3289 if (!Ty->isFirstClassType())
3290 error("PHI node operands must be of first class type");
3291 PHINode *PHI = new PHINode(Ty);
3292 PHI->reserveOperandSpace($2.P->size());
3293 while ($2.P->begin() != $2.P->end()) {
3294 if ($2.P->front().first->getType() != Ty)
3295 error("All elements of a PHI node must be of the same type");
3296 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3301 delete $2.P; // Free the list...
3303 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3305 // Handle the short call syntax
3306 const PointerType *PFTy;
3307 const FunctionType *FTy;
3308 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3309 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3310 // Pull out the types of all of the arguments...
3311 std::vector<const Type*> ParamTypes;
3313 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3315 ParamTypes.push_back((*I).V->getType());
3318 FunctionType::ParamAttrsList ParamAttrs;
3319 if ($2 == OldCallingConv::CSRet) {
3320 ParamAttrs.push_back(FunctionType::NoAttributeSet);
3321 ParamAttrs.push_back(FunctionType::StructRetAttribute);
3323 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3324 if (isVarArg) ParamTypes.pop_back();
3326 const Type *RetTy = $3.PAT->get();
3327 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3328 error("Functions cannot return aggregate types");
3330 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, ParamAttrs);
3331 PFTy = PointerType::get(FTy);
3334 // First upgrade any intrinsic calls.
3335 std::vector<Value*> Args;
3337 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3338 Args.push_back((*$6)[i].V);
3339 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3341 // If we got an upgraded intrinsic
3346 // Get the function we're calling
3347 Value *V = getVal(PFTy, $4);
3349 // Check the argument values match
3350 if (!$6) { // Has no arguments?
3351 // Make sure no arguments is a good thing!
3352 if (FTy->getNumParams() != 0)
3353 error("No arguments passed to a function that expects arguments");
3354 } else { // Has arguments?
3355 // Loop through FunctionType's arguments and ensure they are specified
3358 FunctionType::param_iterator I = FTy->param_begin();
3359 FunctionType::param_iterator E = FTy->param_end();
3360 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3362 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3363 if ((*ArgI).V->getType() != *I)
3364 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3365 (*I)->getDescription() + "'");
3367 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3368 error("Invalid number of parameters detected");
3371 // Create the call instruction
3372 CallInst *CI = new CallInst(V, Args);
3373 CI->setTailCall($1);
3374 CI->setCallingConv(upgradeCallingConv($2));
3387 // IndexList - List of indices for GEP based instructions...
3389 : ',' ValueRefList { $$ = $2; }
3390 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3394 : VOLATILE { $$ = true; }
3395 | /* empty */ { $$ = false; }
3399 : MALLOC Types OptCAlign {
3400 const Type *Ty = $2.PAT->get();
3402 $$.I = new MallocInst(Ty, 0, $3);
3405 | MALLOC Types ',' UINT ValueRef OptCAlign {
3406 const Type *Ty = $2.PAT->get();
3408 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3411 | ALLOCA Types OptCAlign {
3412 const Type *Ty = $2.PAT->get();
3414 $$.I = new AllocaInst(Ty, 0, $3);
3417 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3418 const Type *Ty = $2.PAT->get();
3420 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3423 | FREE ResolvedVal {
3424 const Type *PTy = $2.V->getType();
3425 if (!isa<PointerType>(PTy))
3426 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3427 $$.I = new FreeInst($2.V);
3430 | OptVolatile LOAD Types ValueRef {
3431 const Type* Ty = $3.PAT->get();
3433 if (!isa<PointerType>(Ty))
3434 error("Can't load from nonpointer type: " + Ty->getDescription());
3435 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3436 error("Can't load from pointer of non-first-class type: " +
3437 Ty->getDescription());
3438 Value* tmpVal = getVal(Ty, $4);
3439 $$.I = new LoadInst(tmpVal, "", $1);
3442 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3443 const PointerType *PTy = dyn_cast<PointerType>($5.PAT->get());
3445 error("Can't store to a nonpointer type: " +
3446 $5.PAT->get()->getDescription());
3447 const Type *ElTy = PTy->getElementType();
3448 Value *StoreVal = $3.V;
3449 Value* tmpVal = getVal(PTy, $6);
3450 if (ElTy != $3.V->getType()) {
3451 StoreVal = handleSRetFuncTypeMerge($3.V, ElTy);
3453 error("Can't store '" + $3.V->getType()->getDescription() +
3454 "' into space of type '" + ElTy->getDescription() + "'");
3456 PTy = PointerType::get(StoreVal->getType());
3457 if (Constant *C = dyn_cast<Constant>(tmpVal))
3458 tmpVal = ConstantExpr::getBitCast(C, PTy);
3460 tmpVal = new BitCastInst(tmpVal, PTy, "upgrd.cast", CurBB);
3463 $$.I = new StoreInst(StoreVal, tmpVal, $1);
3467 | GETELEMENTPTR Types ValueRef IndexList {
3468 const Type* Ty = $2.PAT->get();
3469 if (!isa<PointerType>(Ty))
3470 error("getelementptr insn requires pointer operand");
3472 std::vector<Value*> VIndices;
3473 upgradeGEPIndices(Ty, $4, VIndices);
3475 Value* tmpVal = getVal(Ty, $3);
3476 $$.I = new GetElementPtrInst(tmpVal, VIndices);
3485 int yyerror(const char *ErrorMsg) {
3487 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3488 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3489 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3490 if (yychar != YYEMPTY && yychar != 0)
3491 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3493 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3494 std::cout << "llvm-upgrade: parse failed.\n";
3498 void warning(const std::string& ErrorMsg) {
3500 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3501 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3502 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3503 if (yychar != YYEMPTY && yychar != 0)
3504 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3506 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3509 void error(const std::string& ErrorMsg, int LineNo) {
3510 if (LineNo == -1) LineNo = Upgradelineno;
3511 Upgradelineno = LineNo;
3512 yyerror(ErrorMsg.c_str());