SemaExpr.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file was developed by Chris Lattner and is distributed under
  6. // the University of Illinois Open Source License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for expressions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "Sema.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Decl.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/Lex/Preprocessor.h"
  18. #include "clang/Lex/LiteralSupport.h"
  19. #include "clang/Basic/SourceManager.h"
  20. #include "clang/Basic/Diagnostic.h"
  21. #include "clang/Basic/LangOptions.h"
  22. #include "clang/Basic/TargetInfo.h"
  23. #include "llvm/ADT/SmallString.h"
  24. using namespace clang;
  25. /// ParseStringLiteral - The specified tokens were lexed as pasted string
  26. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  27. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  28. /// multiple tokens. However, the common case is that StringToks points to one
  29. /// string.
  30. ///
  31. Action::ExprResult
  32. Sema::ParseStringLiteral(const LexerToken *StringToks, unsigned NumStringToks) {
  33. assert(NumStringToks && "Must have at least one string!");
  34. StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
  35. if (Literal.hadError)
  36. return ExprResult(true);
  37. llvm::SmallVector<SourceLocation, 4> StringTokLocs;
  38. for (unsigned i = 0; i != NumStringToks; ++i)
  39. StringTokLocs.push_back(StringToks[i].getLocation());
  40. // FIXME: handle wchar_t
  41. QualType t = Context.getPointerType(Context.CharTy);
  42. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  43. return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
  44. Literal.AnyWide, t, StringToks[0].getLocation(),
  45. StringToks[NumStringToks-1].getLocation());
  46. }
  47. /// ParseIdentifierExpr - The parser read an identifier in expression context,
  48. /// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
  49. /// identifier is used in an function call context.
  50. Sema::ExprResult Sema::ParseIdentifierExpr(Scope *S, SourceLocation Loc,
  51. IdentifierInfo &II,
  52. bool HasTrailingLParen) {
  53. // Could be enum-constant or decl.
  54. Decl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
  55. if (D == 0) {
  56. // Otherwise, this could be an implicitly declared function reference (legal
  57. // in C90, extension in C99).
  58. if (HasTrailingLParen &&
  59. // Not in C++.
  60. !getLangOptions().CPlusPlus)
  61. D = ImplicitlyDefineFunction(Loc, II, S);
  62. else {
  63. // If this name wasn't predeclared and if this is not a function call,
  64. // diagnose the problem.
  65. return Diag(Loc, diag::err_undeclared_var_use, II.getName());
  66. }
  67. }
  68. if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
  69. return new DeclRefExpr(VD, VD->getType(), Loc);
  70. if (isa<TypedefDecl>(D))
  71. return Diag(Loc, diag::err_unexpected_typedef, II.getName());
  72. assert(0 && "Invalid decl");
  73. }
  74. Sema::ExprResult Sema::ParseSimplePrimaryExpr(SourceLocation Loc,
  75. tok::TokenKind Kind) {
  76. switch (Kind) {
  77. default:
  78. assert(0 && "Unknown simple primary expr!");
  79. // TODO: MOVE this to be some other callback.
  80. case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
  81. case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
  82. case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
  83. return 0;
  84. }
  85. }
  86. Sema::ExprResult Sema::ParseCharacterConstant(const LexerToken &Tok) {
  87. llvm::SmallString<16> CharBuffer;
  88. CharBuffer.resize(Tok.getLength());
  89. const char *ThisTokBegin = &CharBuffer[0];
  90. unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
  91. CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
  92. Tok.getLocation(), PP);
  93. if (Literal.hadError())
  94. return ExprResult(true);
  95. return new CharacterLiteral(Literal.getValue(), Context.IntTy,
  96. Tok.getLocation());
  97. }
  98. Action::ExprResult Sema::ParseNumericConstant(const LexerToken &Tok) {
  99. // fast path for a single digit (which is quite common). A single digit
  100. // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
  101. if (Tok.getLength() == 1) {
  102. const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
  103. unsigned IntSize = Context.Target.getIntWidth(Tok.getLocation());
  104. return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
  105. Context.IntTy,
  106. Tok.getLocation()));
  107. }
  108. llvm::SmallString<512> IntegerBuffer;
  109. IntegerBuffer.resize(Tok.getLength());
  110. const char *ThisTokBegin = &IntegerBuffer[0];
  111. // Get the spelling of the token, which eliminates trigraphs, etc.
  112. unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
  113. NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
  114. Tok.getLocation(), PP);
  115. if (Literal.hadError)
  116. return ExprResult(true);
  117. if (Literal.isIntegerLiteral()) {
  118. QualType t;
  119. // Get the value in the widest-possible width.
  120. llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
  121. if (Literal.GetIntegerValue(ResultVal)) {
  122. // If this value didn't fit into uintmax_t, warn and force to ull.
  123. Diag(Tok.getLocation(), diag::warn_integer_too_large);
  124. t = Context.UnsignedLongLongTy;
  125. assert(Context.getIntegerBitwidth(t, Tok.getLocation()) ==
  126. ResultVal.getBitWidth() && "long long is not intmax_t?");
  127. } else {
  128. // If this value fits into a ULL, try to figure out what else it fits into
  129. // according to the rules of C99 6.4.4.1p5.
  130. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  131. // be an unsigned int.
  132. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  133. // Check from smallest to largest, picking the smallest type we can.
  134. if (!Literal.isLong) { // Are int/unsigned possibilities?
  135. unsigned IntSize = Context.Target.getIntWidth(Tok.getLocation());
  136. // Does it fit in a unsigned int?
  137. if (ResultVal.isIntN(IntSize)) {
  138. // Does it fit in a signed int?
  139. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  140. t = Context.IntTy;
  141. else if (AllowUnsigned)
  142. t = Context.UnsignedIntTy;
  143. }
  144. if (!t.isNull())
  145. ResultVal.trunc(IntSize);
  146. }
  147. // Are long/unsigned long possibilities?
  148. if (t.isNull() && !Literal.isLongLong) {
  149. unsigned LongSize = Context.Target.getLongWidth(Tok.getLocation());
  150. // Does it fit in a unsigned long?
  151. if (ResultVal.isIntN(LongSize)) {
  152. // Does it fit in a signed long?
  153. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  154. t = Context.LongTy;
  155. else if (AllowUnsigned)
  156. t = Context.UnsignedLongTy;
  157. }
  158. if (!t.isNull())
  159. ResultVal.trunc(LongSize);
  160. }
  161. // Finally, check long long if needed.
  162. if (t.isNull()) {
  163. unsigned LongLongSize =
  164. Context.Target.getLongLongWidth(Tok.getLocation());
  165. // Does it fit in a unsigned long long?
  166. if (ResultVal.isIntN(LongLongSize)) {
  167. // Does it fit in a signed long long?
  168. if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
  169. t = Context.LongLongTy;
  170. else if (AllowUnsigned)
  171. t = Context.UnsignedLongLongTy;
  172. }
  173. }
  174. // If we still couldn't decide a type, we probably have something that
  175. // does not fit in a signed long long, but has no U suffix.
  176. if (t.isNull()) {
  177. Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
  178. t = Context.UnsignedLongLongTy;
  179. }
  180. }
  181. return new IntegerLiteral(ResultVal, t, Tok.getLocation());
  182. } else if (Literal.isFloatingLiteral()) {
  183. // FIXME: handle float values > 32 (including compute the real type...).
  184. return new FloatingLiteral(Literal.GetFloatValue(), Context.FloatTy,
  185. Tok.getLocation());
  186. }
  187. return ExprResult(true);
  188. }
  189. Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
  190. ExprTy *Val) {
  191. Expr *e = (Expr *)Val;
  192. assert((e != 0) && "ParseParenExpr() missing expr");
  193. return new ParenExpr(L, R, e);
  194. }
  195. /// The UsualUnaryConversions() function is *not* called by this routine.
  196. /// See C99 6.3.2.1p[2-4] for more details.
  197. QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
  198. SourceLocation OpLoc, bool isSizeof) {
  199. // C99 6.5.3.4p1:
  200. if (isa<FunctionType>(exprType) && isSizeof)
  201. // alignof(function) is allowed.
  202. Diag(OpLoc, diag::ext_sizeof_function_type);
  203. else if (exprType->isVoidType())
  204. Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
  205. else if (exprType->isIncompleteType()) {
  206. Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
  207. diag::err_alignof_incomplete_type,
  208. exprType.getAsString());
  209. return QualType(); // error
  210. }
  211. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  212. return Context.getSizeType();
  213. }
  214. Action::ExprResult Sema::
  215. ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
  216. SourceLocation LPLoc, TypeTy *Ty,
  217. SourceLocation RPLoc) {
  218. // If error parsing type, ignore.
  219. if (Ty == 0) return true;
  220. // Verify that this is a valid expression.
  221. QualType ArgTy = QualType::getFromOpaquePtr(Ty);
  222. QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
  223. if (resultType.isNull())
  224. return true;
  225. return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
  226. }
  227. Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
  228. tok::TokenKind Kind,
  229. ExprTy *Input) {
  230. UnaryOperator::Opcode Opc;
  231. switch (Kind) {
  232. default: assert(0 && "Unknown unary op!");
  233. case tok::plusplus: Opc = UnaryOperator::PostInc; break;
  234. case tok::minusminus: Opc = UnaryOperator::PostDec; break;
  235. }
  236. QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
  237. if (result.isNull())
  238. return true;
  239. return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
  240. }
  241. Action::ExprResult Sema::
  242. ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
  243. ExprTy *Idx, SourceLocation RLoc) {
  244. QualType t1 = ((Expr *)Base)->getType();
  245. QualType t2 = ((Expr *)Idx)->getType();
  246. assert(!t1.isNull() && "no type for array base expression");
  247. assert(!t2.isNull() && "no type for array index expression");
  248. QualType canonT1 = DefaultFunctionArrayConversion(t1).getCanonicalType();
  249. QualType canonT2 = DefaultFunctionArrayConversion(t2).getCanonicalType();
  250. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  251. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  252. // in the subscript position. As a result, we need to derive the array base
  253. // and index from the expression types.
  254. Expr *baseExpr, *indexExpr;
  255. QualType baseType, indexType;
  256. if (isa<PointerType>(canonT1) || isa<VectorType>(canonT1)) {
  257. baseType = canonT1;
  258. indexType = canonT2;
  259. baseExpr = static_cast<Expr *>(Base);
  260. indexExpr = static_cast<Expr *>(Idx);
  261. } else if (isa<PointerType>(canonT2)) { // uncommon
  262. baseType = canonT2;
  263. indexType = canonT1;
  264. baseExpr = static_cast<Expr *>(Idx);
  265. indexExpr = static_cast<Expr *>(Base);
  266. } else {
  267. return Diag(static_cast<Expr *>(Base)->getLocStart(),
  268. diag::err_typecheck_subscript_value,
  269. static_cast<Expr *>(Base)->getSourceRange());
  270. }
  271. // C99 6.5.2.1p1
  272. if (!indexType->isIntegerType()) {
  273. return Diag(indexExpr->getLocStart(), diag::err_typecheck_subscript,
  274. indexExpr->getSourceRange());
  275. }
  276. QualType resultType;
  277. if (PointerType *ary = dyn_cast<PointerType>(baseType)) {
  278. // FIXME: need to deal with const...
  279. resultType = ary->getPointeeType();
  280. // in practice, the following check catches trying to index a pointer
  281. // to a function (e.g. void (*)(int)). Functions are not objects in c99.
  282. if (!resultType->isObjectType()) {
  283. return Diag(baseExpr->getLocStart(),
  284. diag::err_typecheck_subscript_not_object,
  285. baseType.getAsString(), baseExpr->getSourceRange());
  286. }
  287. } else if (VectorType *vec = dyn_cast<VectorType>(baseType))
  288. resultType = vec->getElementType();
  289. return new ArraySubscriptExpr((Expr*)Base, (Expr*)Idx, resultType, RLoc);
  290. }
  291. Action::ExprResult Sema::
  292. ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
  293. tok::TokenKind OpKind, SourceLocation MemberLoc,
  294. IdentifierInfo &Member) {
  295. QualType qualifiedType = ((Expr *)Base)->getType();
  296. assert(!qualifiedType.isNull() && "no type for member expression");
  297. QualType canonType = qualifiedType.getCanonicalType();
  298. if (OpKind == tok::arrow) {
  299. if (PointerType *PT = dyn_cast<PointerType>(canonType)) {
  300. qualifiedType = PT->getPointeeType();
  301. canonType = qualifiedType.getCanonicalType();
  302. } else
  303. return Diag(OpLoc, diag::err_typecheck_member_reference_arrow);
  304. }
  305. if (!isa<RecordType>(canonType))
  306. return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion);
  307. // get the struct/union definition from the type.
  308. RecordDecl *RD = cast<RecordType>(canonType)->getDecl();
  309. if (canonType->isIncompleteType())
  310. return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RD->getName());
  311. FieldDecl *MemberDecl = RD->getMember(&Member);
  312. if (!MemberDecl)
  313. return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName());
  314. return new MemberExpr((Expr*)Base, OpKind == tok::arrow,
  315. MemberDecl, MemberLoc);
  316. }
  317. /// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
  318. /// This provides the location of the left/right parens and a list of comma
  319. /// locations.
  320. Action::ExprResult Sema::
  321. ParseCallExpr(ExprTy *Fn, SourceLocation LParenLoc,
  322. ExprTy **Args, unsigned NumArgsInCall,
  323. SourceLocation *CommaLocs, SourceLocation RParenLoc) {
  324. Expr *funcExpr = (Expr *)Fn;
  325. assert(funcExpr && "no function call expression");
  326. QualType qType = UsualUnaryConversions(funcExpr->getType());
  327. assert(!qType.isNull() && "no type for function call expression");
  328. // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
  329. // type pointer to function".
  330. const PointerType *PT = dyn_cast<PointerType>(qType);
  331. if (PT == 0) PT = dyn_cast<PointerType>(qType.getCanonicalType());
  332. if (PT == 0)
  333. return Diag(funcExpr->getLocStart(), diag::err_typecheck_call_not_function,
  334. SourceRange(funcExpr->getLocStart(), RParenLoc));
  335. const FunctionType *funcT = dyn_cast<FunctionType>(PT->getPointeeType());
  336. if (funcT == 0)
  337. funcT = dyn_cast<FunctionType>(PT->getPointeeType().getCanonicalType());
  338. if (funcT == 0)
  339. return Diag(funcExpr->getLocStart(), diag::err_typecheck_call_not_function,
  340. SourceRange(funcExpr->getLocStart(), RParenLoc));
  341. // If a prototype isn't declared, the parser implicitly defines a func decl
  342. QualType resultType = funcT->getResultType();
  343. if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
  344. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  345. // assignment, to the types of the corresponding parameter, ...
  346. unsigned NumArgsInProto = proto->getNumArgs();
  347. unsigned NumArgsToCheck = NumArgsInCall;
  348. if (NumArgsInCall < NumArgsInProto)
  349. Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
  350. funcExpr->getSourceRange());
  351. else if (NumArgsInCall > NumArgsInProto) {
  352. if (!proto->isVariadic()) {
  353. Diag(((Expr **)Args)[NumArgsInProto+1]->getLocStart(),
  354. diag::err_typecheck_call_too_many_args, funcExpr->getSourceRange(),
  355. ((Expr **)Args)[NumArgsInProto+1]->getSourceRange());
  356. }
  357. NumArgsToCheck = NumArgsInProto;
  358. }
  359. // Continue to check argument types (even if we have too few/many args).
  360. for (unsigned i = 0; i < NumArgsToCheck; i++) {
  361. Expr *argExpr = ((Expr **)Args)[i];
  362. assert(argExpr && "ParseCallExpr(): missing argument expression");
  363. QualType lhsType = proto->getArgType(i);
  364. QualType rhsType = argExpr->getType();
  365. if (lhsType == rhsType) // common case, fast path...
  366. continue;
  367. AssignmentCheckResult result = CheckAssignmentConstraints(lhsType,
  368. rhsType);
  369. SourceLocation l = argExpr->getLocStart();
  370. // decode the result (notice that AST's are still created for extensions).
  371. switch (result) {
  372. case Compatible:
  373. break;
  374. case PointerFromInt:
  375. // check for null pointer constant (C99 6.3.2.3p3)
  376. if (!argExpr->isNullPointerConstant()) {
  377. Diag(l, diag::ext_typecheck_passing_pointer_int,
  378. lhsType.getAsString(), rhsType.getAsString(),
  379. funcExpr->getSourceRange(), argExpr->getSourceRange());
  380. }
  381. break;
  382. case IntFromPointer:
  383. Diag(l, diag::ext_typecheck_passing_pointer_int,
  384. lhsType.getAsString(), rhsType.getAsString(),
  385. funcExpr->getSourceRange(), argExpr->getSourceRange());
  386. break;
  387. case IncompatiblePointer:
  388. Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
  389. rhsType.getAsString(), lhsType.getAsString(),
  390. funcExpr->getSourceRange(), argExpr->getSourceRange());
  391. break;
  392. case CompatiblePointerDiscardsQualifiers:
  393. Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
  394. rhsType.getAsString(), lhsType.getAsString(),
  395. funcExpr->getSourceRange(), argExpr->getSourceRange());
  396. break;
  397. case Incompatible:
  398. return Diag(l, diag::err_typecheck_passing_incompatible,
  399. rhsType.getAsString(), lhsType.getAsString(),
  400. funcExpr->getSourceRange(), argExpr->getSourceRange());
  401. }
  402. }
  403. // Even if the types checked, bail if we had the wrong number of arguments.
  404. if ((NumArgsInCall != NumArgsInProto) && !proto->isVariadic())
  405. return true;
  406. }
  407. return new CallExpr((Expr*)Fn, (Expr**)Args, NumArgsInCall, resultType,
  408. RParenLoc);
  409. }
  410. Action::ExprResult Sema::
  411. ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
  412. SourceLocation RParenLoc, ExprTy *Op) {
  413. // If error parsing type, ignore.
  414. assert((Ty != 0) && "ParseCastExpr(): missing type");
  415. // FIXME: Sema for cast is completely missing.
  416. return new CastExpr(QualType::getFromOpaquePtr(Ty), (Expr*)Op, LParenLoc);
  417. }
  418. inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
  419. Expr *Cond, Expr *LHS, Expr *RHS, SourceLocation questionLoc) {
  420. QualType cond = Cond->getType();
  421. QualType lhs = LHS->getType();
  422. QualType rhs = RHS->getType();
  423. assert(!cond.isNull() && "ParseConditionalOp(): no conditional type");
  424. assert(!lhs.isNull() && "ParseConditionalOp(): no lhs type");
  425. assert(!rhs.isNull() && "ParseConditionalOp(): no rhs type");
  426. cond = UsualUnaryConversions(cond);
  427. lhs = UsualUnaryConversions(lhs);
  428. rhs = UsualUnaryConversions(rhs);
  429. // first, check the condition.
  430. if (!cond->isScalarType()) { // C99 6.5.15p2
  431. Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
  432. cond.getAsString());
  433. return QualType();
  434. }
  435. // now check the two expressions.
  436. if (lhs->isArithmeticType() && rhs->isArithmeticType()) // C99 6.5.15p3,5
  437. return UsualArithmeticConversions(lhs, rhs);
  438. if ((lhs->isStructureType() && rhs->isStructureType()) || // C99 6.5.15p3
  439. (lhs->isUnionType() && rhs->isUnionType())) {
  440. TagType *lTag = cast<TagType>(lhs.getCanonicalType());
  441. TagType *rTag = cast<TagType>(rhs.getCanonicalType());
  442. if (lTag->getDecl()->getIdentifier() == rTag->getDecl()->getIdentifier())
  443. return lhs;
  444. else {
  445. Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
  446. lhs.getAsString(), rhs.getAsString(),
  447. LHS->getSourceRange(), RHS->getSourceRange());
  448. return QualType();
  449. }
  450. }
  451. if (lhs->isPointerType() && RHS->isNullPointerConstant()) // C99 6.5.15p3
  452. return lhs;
  453. if (rhs->isPointerType() && LHS->isNullPointerConstant())
  454. return rhs;
  455. if (lhs->isPointerType() && rhs->isPointerType()) { // C99 6.5.15p3,6
  456. QualType lhptee, rhptee;
  457. // get the "pointed to" type
  458. lhptee = cast<PointerType>(lhs.getCanonicalType())->getPointeeType();
  459. rhptee = cast<PointerType>(rhs.getCanonicalType())->getPointeeType();
  460. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  461. if (lhptee.getUnqualifiedType()->isVoidType() &&
  462. (rhptee->isObjectType() || rhptee->isIncompleteType()))
  463. return lhs;
  464. if (rhptee.getUnqualifiedType()->isVoidType() &&
  465. (lhptee->isObjectType() || lhptee->isIncompleteType()))
  466. return rhs;
  467. // FIXME: C99 6.5.15p6: If both operands are pointers to compatible types
  468. // *or* to differently qualified versions of compatible types, the result
  469. // type is a pointer to an appropriately qualified version of the
  470. // *composite* type.
  471. if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
  472. rhptee.getUnqualifiedType())) {
  473. Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
  474. lhs.getAsString(), rhs.getAsString(),
  475. LHS->getSourceRange(), RHS->getSourceRange());
  476. return lhs; // FIXME: this is an _ext - is this return o.k?
  477. }
  478. }
  479. if (lhs->isVoidType() && rhs->isVoidType()) // C99 6.5.15p3
  480. return lhs;
  481. Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
  482. lhs.getAsString(), rhs.getAsString(),
  483. LHS->getSourceRange(), RHS->getSourceRange());
  484. return QualType();
  485. }
  486. /// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  487. /// in the case of a the GNU conditional expr extension.
  488. Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
  489. SourceLocation ColonLoc,
  490. ExprTy *Cond, ExprTy *LHS,
  491. ExprTy *RHS) {
  492. QualType result = CheckConditionalOperands((Expr *)Cond, (Expr *)LHS,
  493. (Expr *)RHS, QuestionLoc);
  494. if (result.isNull())
  495. return true;
  496. return new ConditionalOperator((Expr*)Cond, (Expr*)LHS, (Expr*)RHS, result);
  497. }
  498. inline QualType Sema::DefaultFunctionArrayConversion(QualType t) {
  499. if (t->isFunctionType()) // C99 6.3.2.1p4
  500. return Context.getPointerType(t);
  501. if (const ArrayType *ary = dyn_cast<ArrayType>(t.getCanonicalType()))
  502. return Context.getPointerType(ary->getElementType()); // C99 6.3.2.1p3
  503. return t;
  504. }
  505. /// UsualUnaryConversion - Performs various conversions that are common to most
  506. /// operators (C99 6.3). The conversions of array and function types are
  507. /// sometimes surpressed. For example, the array->pointer conversion doesn't
  508. /// apply if the array is an argument to the sizeof or address (&) operators.
  509. /// In these instances, this routine should *not* be called.
  510. QualType Sema::UsualUnaryConversions(QualType t) {
  511. assert(!t.isNull() && "UsualUnaryConversions - missing type");
  512. if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
  513. return Context.IntTy;
  514. return DefaultFunctionArrayConversion(t);
  515. }
  516. /// UsualArithmeticConversions - Performs various conversions that are common to
  517. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  518. /// routine returns the first non-arithmetic type found. The client is
  519. /// responsible for emitting appropriate error diagnostics.
  520. QualType Sema::UsualArithmeticConversions(QualType &lhs, QualType &rhs) {
  521. lhs = UsualUnaryConversions(lhs);
  522. rhs = UsualUnaryConversions(rhs);
  523. // If both types are identical, no conversion is needed.
  524. if (lhs == rhs)
  525. return lhs;
  526. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  527. // The caller can deal with this (e.g. pointer + int).
  528. if (!lhs->isArithmeticType())
  529. return lhs;
  530. if (!rhs->isArithmeticType())
  531. return rhs;
  532. // At this point, we have two different arithmetic types.
  533. // Handle complex types first (C99 6.3.1.8p1).
  534. if (lhs->isComplexType() || rhs->isComplexType()) {
  535. // if we have an integer operand, the result is the complex type.
  536. if (rhs->isIntegerType())
  537. return lhs;
  538. if (lhs->isIntegerType())
  539. return rhs;
  540. return Context.maxComplexType(lhs, rhs);
  541. }
  542. // Now handle "real" floating types (i.e. float, double, long double).
  543. if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
  544. // if we have an integer operand, the result is the real floating type.
  545. if (rhs->isIntegerType())
  546. return lhs;
  547. if (lhs->isIntegerType())
  548. return rhs;
  549. // we have two real floating types, float/complex combos were handled above.
  550. return Context.maxFloatingType(lhs, rhs);
  551. }
  552. return Context.maxIntegerType(lhs, rhs);
  553. }
  554. // CheckPointerTypesForAssignment - This is a very tricky routine (despite
  555. // being closely modeled after the C99 spec:-). The odd characteristic of this
  556. // routine is it effectively iqnores the qualifiers on the top level pointee.
  557. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  558. // FIXME: add a couple examples in this comment.
  559. Sema::AssignmentCheckResult
  560. Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
  561. QualType lhptee, rhptee;
  562. // get the "pointed to" type (ignoring qualifiers at the top level)
  563. lhptee = cast<PointerType>(lhsType.getCanonicalType())->getPointeeType();
  564. rhptee = cast<PointerType>(rhsType.getCanonicalType())->getPointeeType();
  565. // make sure we operate on the canonical type
  566. lhptee = lhptee.getCanonicalType();
  567. rhptee = rhptee.getCanonicalType();
  568. AssignmentCheckResult r = Compatible;
  569. // C99 6.5.16.1p1: This following citation is common to constraints
  570. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  571. // qualifiers of the type *pointed to* by the right;
  572. if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
  573. rhptee.getQualifiers())
  574. r = CompatiblePointerDiscardsQualifiers;
  575. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  576. // incomplete type and the other is a pointer to a qualified or unqualified
  577. // version of void...
  578. if (lhptee.getUnqualifiedType()->isVoidType() &&
  579. (rhptee->isObjectType() || rhptee->isIncompleteType()))
  580. ;
  581. else if (rhptee.getUnqualifiedType()->isVoidType() &&
  582. (lhptee->isObjectType() || lhptee->isIncompleteType()))
  583. ;
  584. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  585. // unqualified versions of compatible types, ...
  586. else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
  587. rhptee.getUnqualifiedType()))
  588. r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
  589. return r;
  590. }
  591. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  592. /// has code to accommodate several GCC extensions when type checking
  593. /// pointers. Here are some objectionable examples that GCC considers warnings:
  594. ///
  595. /// int a, *pint;
  596. /// short *pshort;
  597. /// struct foo *pfoo;
  598. ///
  599. /// pint = pshort; // warning: assignment from incompatible pointer type
  600. /// a = pint; // warning: assignment makes integer from pointer without a cast
  601. /// pint = a; // warning: assignment makes pointer from integer without a cast
  602. /// pint = pfoo; // warning: assignment from incompatible pointer type
  603. ///
  604. /// As a result, the code for dealing with pointers is more complex than the
  605. /// C99 spec dictates.
  606. /// Note: the warning above turn into errors when -pedantic-errors is enabled.
  607. ///
  608. Sema::AssignmentCheckResult
  609. Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
  610. // This check seems unnatural, however it is necessary to insure the proper
  611. // conversion of functions/arrays. If the conversion were done for all
  612. // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
  613. // expressions that surpress this implicit conversion (&, sizeof).
  614. rhsType = DefaultFunctionArrayConversion(rhsType);
  615. if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
  616. if (lhsType->isVectorType() || rhsType->isVectorType()) {
  617. if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
  618. return Incompatible;
  619. }
  620. return Compatible;
  621. } else if (lhsType->isPointerType()) {
  622. if (rhsType->isIntegerType())
  623. return PointerFromInt;
  624. if (rhsType->isPointerType())
  625. return CheckPointerTypesForAssignment(lhsType, rhsType);
  626. } else if (rhsType->isPointerType()) {
  627. // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
  628. if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
  629. return IntFromPointer;
  630. if (lhsType->isPointerType())
  631. return CheckPointerTypesForAssignment(lhsType, rhsType);
  632. } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
  633. if (Type::tagTypesAreCompatible(lhsType, rhsType))
  634. return Compatible;
  635. } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
  636. if (Type::referenceTypesAreCompatible(lhsType, rhsType))
  637. return Compatible;
  638. }
  639. return Incompatible;
  640. }
  641. inline void Sema::InvalidOperands(SourceLocation loc, Expr *lex, Expr *rex) {
  642. Diag(loc, diag::err_typecheck_invalid_operands,
  643. lex->getType().getAsString(), rex->getType().getAsString(),
  644. lex->getSourceRange(), rex->getSourceRange());
  645. }
  646. inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *lex,
  647. Expr *rex) {
  648. QualType lhsType = lex->getType(), rhsType = rex->getType();
  649. // make sure the vector types are identical.
  650. if (lhsType == rhsType)
  651. return lhsType;
  652. // You cannot convert between vector values of different size.
  653. Diag(loc, diag::err_typecheck_vector_not_convertable,
  654. lex->getType().getAsString(), rex->getType().getAsString(),
  655. lex->getSourceRange(), rex->getSourceRange());
  656. return QualType();
  657. }
  658. inline QualType Sema::CheckMultiplyDivideOperands(
  659. Expr *lex, Expr *rex, SourceLocation loc)
  660. {
  661. QualType lhsType = lex->getType(), rhsType = rex->getType();
  662. if (lhsType->isVectorType() || rhsType->isVectorType())
  663. return CheckVectorOperands(loc, lex, rex);
  664. QualType resType = UsualArithmeticConversions(lhsType, rhsType);
  665. if (resType->isArithmeticType())
  666. return resType;
  667. InvalidOperands(loc, lex, rex);
  668. return QualType();
  669. }
  670. inline QualType Sema::CheckRemainderOperands(
  671. Expr *lex, Expr *rex, SourceLocation loc)
  672. {
  673. QualType lhsType = lex->getType(), rhsType = rex->getType();
  674. QualType resType = UsualArithmeticConversions(lhsType, rhsType);
  675. if (resType->isIntegerType())
  676. return resType;
  677. InvalidOperands(loc, lex, rex);
  678. return QualType();
  679. }
  680. inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
  681. Expr *lex, Expr *rex, SourceLocation loc)
  682. {
  683. QualType lhsType = lex->getType(), rhsType = rex->getType();
  684. if (lhsType->isVectorType() || rhsType->isVectorType())
  685. return CheckVectorOperands(loc, lex, rex);
  686. QualType resType = UsualArithmeticConversions(lhsType, rhsType);
  687. // handle the common case first (both operands are arithmetic).
  688. if (resType->isArithmeticType())
  689. return resType;
  690. if ((lhsType->isPointerType() && rhsType->isIntegerType()) ||
  691. (lhsType->isIntegerType() && rhsType->isPointerType()))
  692. return resType;
  693. InvalidOperands(loc, lex, rex);
  694. return QualType();
  695. }
  696. inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
  697. Expr *lex, Expr *rex, SourceLocation loc)
  698. {
  699. QualType lhsType = lex->getType(), rhsType = rex->getType();
  700. if (lhsType->isVectorType() || rhsType->isVectorType())
  701. return CheckVectorOperands(loc, lex, rex);
  702. QualType resType = UsualArithmeticConversions(lhsType, rhsType);
  703. // handle the common case first (both operands are arithmetic).
  704. if (resType->isArithmeticType())
  705. return resType;
  706. if ((lhsType->isPointerType() && rhsType->isIntegerType()) ||
  707. (lhsType->isPointerType() && rhsType->isPointerType()))
  708. return resType;
  709. InvalidOperands(loc, lex, rex);
  710. return QualType();
  711. }
  712. inline QualType Sema::CheckShiftOperands( // C99 6.5.7
  713. Expr *lex, Expr *rex, SourceLocation loc)
  714. {
  715. // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
  716. // for int << longlong -> the result type should be int, not long long.
  717. QualType lhsType = lex->getType(), rhsType = rex->getType();
  718. QualType resType = UsualArithmeticConversions(lhsType, rhsType);
  719. if (resType->isIntegerType())
  720. return resType;
  721. InvalidOperands(loc, lex, rex);
  722. return QualType();
  723. }
  724. inline QualType Sema::CheckRelationalOperands( // C99 6.5.8
  725. Expr *lex, Expr *rex, SourceLocation loc)
  726. {
  727. QualType lType = UsualUnaryConversions(lex->getType());
  728. QualType rType = UsualUnaryConversions(rex->getType());
  729. if (lType->isRealType() && rType->isRealType())
  730. return Context.IntTy;
  731. if (lType->isPointerType()) {
  732. if (rType->isPointerType())
  733. return Context.IntTy;
  734. if (rType->isIntegerType()) {
  735. if (!rex->isNullPointerConstant())
  736. Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
  737. lex->getSourceRange(), rex->getSourceRange());
  738. return Context.IntTy; // the previous diagnostic is a GCC extension.
  739. }
  740. } else if (rType->isPointerType()) {
  741. if (lType->isIntegerType()) {
  742. if (!lex->isNullPointerConstant())
  743. Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
  744. lex->getSourceRange(), rex->getSourceRange());
  745. return Context.IntTy; // the previous diagnostic is a GCC extension.
  746. }
  747. }
  748. InvalidOperands(loc, lex, rex);
  749. return QualType();
  750. }
  751. inline QualType Sema::CheckEqualityOperands( // C99 6.5.9
  752. Expr *lex, Expr *rex, SourceLocation loc)
  753. {
  754. QualType lType = UsualUnaryConversions(lex->getType());
  755. QualType rType = UsualUnaryConversions(rex->getType());
  756. if (lType->isArithmeticType() && rType->isArithmeticType())
  757. return Context.IntTy;
  758. if (lType->isPointerType()) {
  759. if (rType->isPointerType())
  760. return Context.IntTy;
  761. if (rType->isIntegerType()) {
  762. if (!rex->isNullPointerConstant())
  763. Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
  764. lex->getSourceRange(), rex->getSourceRange());
  765. return Context.IntTy; // the previous diagnostic is a GCC extension.
  766. }
  767. } else if (rType->isPointerType()) {
  768. if (lType->isIntegerType()) {
  769. if (!lex->isNullPointerConstant())
  770. Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
  771. lex->getSourceRange(), rex->getSourceRange());
  772. return Context.IntTy; // the previous diagnostic is a GCC extension.
  773. }
  774. }
  775. InvalidOperands(loc, lex, rex);
  776. return QualType();
  777. }
  778. inline QualType Sema::CheckBitwiseOperands(
  779. Expr *lex, Expr *rex, SourceLocation loc)
  780. {
  781. QualType lhsType = lex->getType(), rhsType = rex->getType();
  782. if (lhsType->isVectorType() || rhsType->isVectorType())
  783. return CheckVectorOperands(loc, lex, rex);
  784. QualType resType = UsualArithmeticConversions(lhsType, rhsType);
  785. if (resType->isIntegerType())
  786. return resType;
  787. InvalidOperands(loc, lex, rex);
  788. return QualType();
  789. }
  790. inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
  791. Expr *lex, Expr *rex, SourceLocation loc)
  792. {
  793. QualType lhsType = UsualUnaryConversions(lex->getType());
  794. QualType rhsType = UsualUnaryConversions(rex->getType());
  795. if (lhsType->isScalarType() || rhsType->isScalarType())
  796. return Context.IntTy;
  797. InvalidOperands(loc, lex, rex);
  798. return QualType();
  799. }
  800. inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
  801. Expr *lex, Expr *rex, SourceLocation loc, QualType compoundType)
  802. {
  803. QualType lhsType = lex->getType();
  804. QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
  805. bool hadError = false;
  806. Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
  807. switch (mlval) { // C99 6.5.16p2
  808. case Expr::MLV_Valid:
  809. break;
  810. case Expr::MLV_ConstQualified:
  811. Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
  812. hadError = true;
  813. break;
  814. case Expr::MLV_ArrayType:
  815. Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
  816. lhsType.getAsString(), lex->getSourceRange());
  817. return QualType();
  818. case Expr::MLV_NotObjectType:
  819. Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
  820. lhsType.getAsString(), lex->getSourceRange());
  821. return QualType();
  822. case Expr::MLV_InvalidExpression:
  823. Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
  824. lex->getSourceRange());
  825. return QualType();
  826. case Expr::MLV_IncompleteType:
  827. case Expr::MLV_IncompleteVoidType:
  828. Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
  829. lhsType.getAsString(), lex->getSourceRange());
  830. return QualType();
  831. }
  832. if (lhsType == rhsType) // common case, fast path...
  833. return lhsType;
  834. AssignmentCheckResult result = CheckAssignmentConstraints(lhsType, rhsType);
  835. // decode the result (notice that extensions still return a type).
  836. switch (result) {
  837. case Compatible:
  838. break;
  839. case Incompatible:
  840. Diag(loc, diag::err_typecheck_assign_incompatible,
  841. lhsType.getAsString(), rhsType.getAsString(),
  842. lex->getSourceRange(), rex->getSourceRange());
  843. hadError = true;
  844. break;
  845. case PointerFromInt:
  846. // check for null pointer constant (C99 6.3.2.3p3)
  847. if (compoundType.isNull() && !rex->isNullPointerConstant()) {
  848. Diag(loc, diag::ext_typecheck_assign_pointer_int,
  849. lhsType.getAsString(), rhsType.getAsString(),
  850. lex->getSourceRange(), rex->getSourceRange());
  851. }
  852. break;
  853. case IntFromPointer:
  854. Diag(loc, diag::ext_typecheck_assign_pointer_int,
  855. lhsType.getAsString(), rhsType.getAsString(),
  856. lex->getSourceRange(), rex->getSourceRange());
  857. break;
  858. case IncompatiblePointer:
  859. Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
  860. lhsType.getAsString(), rhsType.getAsString(),
  861. lex->getSourceRange(), rex->getSourceRange());
  862. break;
  863. case CompatiblePointerDiscardsQualifiers:
  864. Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
  865. lhsType.getAsString(), rhsType.getAsString(),
  866. lex->getSourceRange(), rex->getSourceRange());
  867. break;
  868. }
  869. // C99 6.5.16p3: The type of an assignment expression is the type of the
  870. // left operand unless the left operand has qualified type, in which case
  871. // it is the unqualified version of the type of the left operand.
  872. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  873. // is converted to the type of the assignment expression (above).
  874. // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
  875. return hadError ? QualType() : lhsType.getUnqualifiedType();
  876. }
  877. inline QualType Sema::CheckCommaOperands( // C99 6.5.17
  878. Expr *lex, Expr *rex, SourceLocation loc) {
  879. return UsualUnaryConversions(rex->getType());
  880. }
  881. QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
  882. QualType lhsType = op->getType(), rhsType = Context.IntTy;
  883. QualType resType = UsualArithmeticConversions(lhsType, rhsType);
  884. assert(!resType.isNull() && "no type for increment/decrement expression");
  885. // C99 6.5.2.4p1
  886. if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
  887. if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
  888. Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
  889. resType.getAsString(), op->getSourceRange());
  890. return QualType();
  891. }
  892. } else if (!resType->isRealType()) {
  893. // FIXME: Allow Complex as a GCC extension.
  894. Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
  895. resType.getAsString(), op->getSourceRange());
  896. return QualType();
  897. }
  898. // At this point, we know we have a real or pointer type. Now make sure
  899. // the operand is a modifiable lvalue.
  900. Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
  901. if (mlval != Expr::MLV_Valid) {
  902. // FIXME: emit a more precise diagnostic...
  903. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
  904. op->getSourceRange());
  905. return QualType();
  906. }
  907. return resType;
  908. }
  909. /// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
  910. /// This routine allows us to typecheck complex/recursive expressions
  911. /// where the declaration is needed for type checking. Here are some
  912. /// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
  913. static Decl *getPrimaryDeclaration(Expr *e) {
  914. switch (e->getStmtClass()) {
  915. case Stmt::DeclRefExprClass:
  916. return cast<DeclRefExpr>(e)->getDecl();
  917. case Stmt::MemberExprClass:
  918. return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
  919. case Stmt::ArraySubscriptExprClass:
  920. return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
  921. case Stmt::CallExprClass:
  922. return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
  923. case Stmt::UnaryOperatorClass:
  924. return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
  925. case Stmt::ParenExprClass:
  926. return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
  927. default:
  928. return 0;
  929. }
  930. }
  931. /// CheckAddressOfOperand - The operand of & must be either a function
  932. /// designator or an lvalue designating an object. If it is an lvalue, the
  933. /// object cannot be declared with storage class register or be a bit field.
  934. /// Note: The usual conversions are *not* applied to the operand of the &
  935. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  936. QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
  937. Decl *dcl = getPrimaryDeclaration(op);
  938. Expr::isLvalueResult lval = op->isLvalue();
  939. if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
  940. if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
  941. ;
  942. else { // FIXME: emit more specific diag...
  943. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
  944. op->getSourceRange());
  945. return QualType();
  946. }
  947. } else if (dcl) {
  948. // We have an lvalue with a decl. Make sure the decl is not declared
  949. // with the register storage-class specifier.
  950. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  951. if (vd->getStorageClass() == VarDecl::Register) {
  952. Diag(OpLoc, diag::err_typecheck_address_of_register,
  953. op->getSourceRange());
  954. return QualType();
  955. }
  956. } else
  957. assert(0 && "Unknown/unexpected decl type");
  958. // FIXME: add check for bitfields!
  959. }
  960. // If the operand has type "type", the result has type "pointer to type".
  961. return Context.getPointerType(op->getType());
  962. }
  963. QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
  964. QualType qType = UsualUnaryConversions(op->getType());
  965. assert(!qType.isNull() && "no type for * expression");
  966. if (PointerType *PT = dyn_cast<PointerType>(qType.getCanonicalType())) {
  967. QualType ptype = PT->getPointeeType();
  968. // C99 6.5.3.2p4. "if it points to an object,...".
  969. if (ptype->isIncompleteType()) { // An incomplete type is not an object
  970. // GCC compat: special case 'void *' (treat as warning).
  971. if (ptype->isVoidType()) {
  972. Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
  973. qType.getAsString(), op->getSourceRange());
  974. } else {
  975. Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
  976. ptype.getAsString(), op->getSourceRange());
  977. return QualType();
  978. }
  979. }
  980. return ptype;
  981. }
  982. Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
  983. qType.getAsString(), op->getSourceRange());
  984. return QualType();
  985. }
  986. static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
  987. tok::TokenKind Kind) {
  988. BinaryOperator::Opcode Opc;
  989. switch (Kind) {
  990. default: assert(0 && "Unknown binop!");
  991. case tok::star: Opc = BinaryOperator::Mul; break;
  992. case tok::slash: Opc = BinaryOperator::Div; break;
  993. case tok::percent: Opc = BinaryOperator::Rem; break;
  994. case tok::plus: Opc = BinaryOperator::Add; break;
  995. case tok::minus: Opc = BinaryOperator::Sub; break;
  996. case tok::lessless: Opc = BinaryOperator::Shl; break;
  997. case tok::greatergreater: Opc = BinaryOperator::Shr; break;
  998. case tok::lessequal: Opc = BinaryOperator::LE; break;
  999. case tok::less: Opc = BinaryOperator::LT; break;
  1000. case tok::greaterequal: Opc = BinaryOperator::GE; break;
  1001. case tok::greater: Opc = BinaryOperator::GT; break;
  1002. case tok::exclaimequal: Opc = BinaryOperator::NE; break;
  1003. case tok::equalequal: Opc = BinaryOperator::EQ; break;
  1004. case tok::amp: Opc = BinaryOperator::And; break;
  1005. case tok::caret: Opc = BinaryOperator::Xor; break;
  1006. case tok::pipe: Opc = BinaryOperator::Or; break;
  1007. case tok::ampamp: Opc = BinaryOperator::LAnd; break;
  1008. case tok::pipepipe: Opc = BinaryOperator::LOr; break;
  1009. case tok::equal: Opc = BinaryOperator::Assign; break;
  1010. case tok::starequal: Opc = BinaryOperator::MulAssign; break;
  1011. case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
  1012. case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
  1013. case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
  1014. case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
  1015. case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
  1016. case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
  1017. case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
  1018. case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
  1019. case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
  1020. case tok::comma: Opc = BinaryOperator::Comma; break;
  1021. }
  1022. return Opc;
  1023. }
  1024. static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
  1025. tok::TokenKind Kind) {
  1026. UnaryOperator::Opcode Opc;
  1027. switch (Kind) {
  1028. default: assert(0 && "Unknown unary op!");
  1029. case tok::plusplus: Opc = UnaryOperator::PreInc; break;
  1030. case tok::minusminus: Opc = UnaryOperator::PreDec; break;
  1031. case tok::amp: Opc = UnaryOperator::AddrOf; break;
  1032. case tok::star: Opc = UnaryOperator::Deref; break;
  1033. case tok::plus: Opc = UnaryOperator::Plus; break;
  1034. case tok::minus: Opc = UnaryOperator::Minus; break;
  1035. case tok::tilde: Opc = UnaryOperator::Not; break;
  1036. case tok::exclaim: Opc = UnaryOperator::LNot; break;
  1037. case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
  1038. case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
  1039. case tok::kw___real: Opc = UnaryOperator::Real; break;
  1040. case tok::kw___imag: Opc = UnaryOperator::Imag; break;
  1041. case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
  1042. }
  1043. return Opc;
  1044. }
  1045. // Binary Operators. 'Tok' is the token for the operator.
  1046. Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
  1047. ExprTy *LHS, ExprTy *RHS) {
  1048. BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
  1049. Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
  1050. assert((lhs != 0) && "ParseBinOp(): missing left expression");
  1051. assert((rhs != 0) && "ParseBinOp(): missing right expression");
  1052. QualType ResultTy; // Result type of the binary operator.
  1053. QualType CompTy; // Computation type for compound assignments (e.g. '+=')
  1054. switch (Opc) {
  1055. default:
  1056. assert(0 && "Unknown binary expr!");
  1057. case BinaryOperator::Assign:
  1058. ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
  1059. break;
  1060. case BinaryOperator::Mul:
  1061. case BinaryOperator::Div:
  1062. ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
  1063. break;
  1064. case BinaryOperator::Rem:
  1065. ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
  1066. break;
  1067. case BinaryOperator::Add:
  1068. ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
  1069. break;
  1070. case BinaryOperator::Sub:
  1071. ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
  1072. break;
  1073. case BinaryOperator::Shl:
  1074. case BinaryOperator::Shr:
  1075. ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
  1076. break;
  1077. case BinaryOperator::LE:
  1078. case BinaryOperator::LT:
  1079. case BinaryOperator::GE:
  1080. case BinaryOperator::GT:
  1081. ResultTy = CheckRelationalOperands(lhs, rhs, TokLoc);
  1082. break;
  1083. case BinaryOperator::EQ:
  1084. case BinaryOperator::NE:
  1085. ResultTy = CheckEqualityOperands(lhs, rhs, TokLoc);
  1086. break;
  1087. case BinaryOperator::And:
  1088. case BinaryOperator::Xor:
  1089. case BinaryOperator::Or:
  1090. ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
  1091. break;
  1092. case BinaryOperator::LAnd:
  1093. case BinaryOperator::LOr:
  1094. ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
  1095. break;
  1096. case BinaryOperator::MulAssign:
  1097. case BinaryOperator::DivAssign:
  1098. CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
  1099. if (!CompTy.isNull())
  1100. ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
  1101. break;
  1102. case BinaryOperator::RemAssign:
  1103. CompTy = CheckRemainderOperands(lhs, rhs, TokLoc);
  1104. if (!CompTy.isNull())
  1105. ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
  1106. break;
  1107. case BinaryOperator::AddAssign:
  1108. CompTy = CheckAdditionOperands(lhs, rhs, TokLoc);
  1109. if (!CompTy.isNull())
  1110. ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
  1111. break;
  1112. case BinaryOperator::SubAssign:
  1113. CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
  1114. if (!CompTy.isNull())
  1115. ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
  1116. break;
  1117. case BinaryOperator::ShlAssign:
  1118. case BinaryOperator::ShrAssign:
  1119. CompTy = CheckShiftOperands(lhs, rhs, TokLoc);
  1120. if (!CompTy.isNull())
  1121. ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
  1122. break;
  1123. case BinaryOperator::AndAssign:
  1124. case BinaryOperator::XorAssign:
  1125. case BinaryOperator::OrAssign:
  1126. CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
  1127. if (!CompTy.isNull())
  1128. ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
  1129. break;
  1130. case BinaryOperator::Comma:
  1131. ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
  1132. break;
  1133. }
  1134. if (ResultTy.isNull())
  1135. return true;
  1136. if (CompTy.isNull())
  1137. return new BinaryOperator(lhs, rhs, Opc, ResultTy);
  1138. else
  1139. return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy);
  1140. }
  1141. // Unary Operators. 'Tok' is the token for the operator.
  1142. Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
  1143. ExprTy *input) {
  1144. Expr *Input = (Expr*)input;
  1145. UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
  1146. QualType resultType;
  1147. switch (Opc) {
  1148. default:
  1149. assert(0 && "Unimplemented unary expr!");
  1150. case UnaryOperator::PreInc:
  1151. case UnaryOperator::PreDec:
  1152. resultType = CheckIncrementDecrementOperand(Input, OpLoc);
  1153. break;
  1154. case UnaryOperator::AddrOf:
  1155. resultType = CheckAddressOfOperand(Input, OpLoc);
  1156. break;
  1157. case UnaryOperator::Deref:
  1158. resultType = CheckIndirectionOperand(Input, OpLoc);
  1159. break;
  1160. case UnaryOperator::Plus:
  1161. case UnaryOperator::Minus:
  1162. resultType = UsualUnaryConversions(Input->getType());
  1163. if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
  1164. return Diag(OpLoc, diag::err_typecheck_unary_expr,
  1165. resultType.getAsString());
  1166. break;
  1167. case UnaryOperator::Not: // bitwise complement
  1168. if (Input->getType()->isVectorType())
  1169. resultType = Input->getType();
  1170. else {
  1171. resultType = UsualUnaryConversions(Input->getType());
  1172. if (!resultType->isIntegerType()) // C99 6.5.3.3p1
  1173. return Diag(OpLoc, diag::err_typecheck_unary_expr,
  1174. resultType.getAsString());
  1175. }
  1176. break;
  1177. case UnaryOperator::LNot: // logical negation
  1178. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  1179. resultType = DefaultFunctionArrayConversion(Input->getType());
  1180. if (!resultType->isScalarType()) // C99 6.5.3.3p1
  1181. return Diag(OpLoc, diag::err_typecheck_unary_expr,
  1182. resultType.getAsString());
  1183. // LNot always has type int. C99 6.5.3.3p5.
  1184. resultType = Context.IntTy;
  1185. break;
  1186. case UnaryOperator::SizeOf:
  1187. resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
  1188. break;
  1189. case UnaryOperator::AlignOf:
  1190. resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
  1191. break;
  1192. case UnaryOperator::Extension:
  1193. // FIXME: does __extension__ cause any promotions? I would think not.
  1194. resultType = Input->getType();
  1195. break;
  1196. }
  1197. if (resultType.isNull())
  1198. return true;
  1199. return new UnaryOperator(Input, Opc, resultType, OpLoc);
  1200. }
  1201. /// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
  1202. Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
  1203. SourceLocation LabLoc,
  1204. IdentifierInfo *LabelII) {
  1205. // Look up the record for this label identifier.
  1206. LabelStmt *&LabelDecl = LabelMap[LabelII];
  1207. // If we haven't seen this label yet, create a forward reference.
  1208. if (LabelDecl == 0)
  1209. LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
  1210. // Create the AST node. The address of a label always has type 'void*'.
  1211. return new AddrLabel(OpLoc, LabLoc, LabelDecl,
  1212. Context.getPointerType(Context.VoidTy));
  1213. }